3 ms·
Don't write code like this... trying to fake sum types in an object oriented language ends up being a horrible, hard to maintain mess, similar to those examples
by emmanueloga_ 6y ago
Don't write code like this... trying to fake sum types in an object oriented language ends up being a horrible, hard to maintain mess, similar to those examples on the original post.
Typescript's "discriminated unions" [1] make for incredibly inelegant looking code for anything but the most basic sum types, the ergonomics are nothing like the experience of using Haskell or OCaml.
I love sum types but in an OOP the equivalent implementation is the visitor pattern (if the problem calls for it). I was once starry eyed about "making invalid states irrepresentable". I even managed to introduce a code generator to bolt sum types into a production Dart app. My colleagues loved it (not) :-)
Thing is, programs have this annoying tendency of being incorrect no matter what technique you use :-), there's no silver bullet! If a pattern is natural for a given language, it is better to use that pattern than to force it to be something it isn't.
1: https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#union-exhaustiveness-checking https://www.typescriptlang.org/docs/handbook/unions-and-inte...
- moomin 6y agoThe joke is, OO language have sum types, albeit incredibly broken ones, because any set of classes that inherits from the same base has the base as a sum type. You can surface this by implementing the visitor pattern.