19 ms·
Discriminated union is low-level pattern from non-OO languages (it is common pattern in C, Pascal has syntax for this and IIRC unions are always discriminated i
by dfox 9y ago
Discriminated union is low-level pattern from non-OO languages (it is common pattern in C, Pascal has syntax for this and IIRC unions are always discriminated in "standard" Pascal)
In object oriented languages this pattern is mostly unnecessary, because inheritance is usually better solution for the same problem. Only reason to use something like this in C++ is (maybe even only perceived) efficiency gained by removing level of pointer indirection.
- xyzzyz 9y agoThe sum type, which the author is talking about, is not the same as "discriminated union" pattern, the latter being the crude implementation of the former. It really comes from functional languages like ML, and is extremely useful and convenient when combined with pattern matching. In fact, attempts to emulate it in OOP using interfaces and visitor pattern tend to bring a lot of boilerplate, and obscure the actual logic, which is exactly what the author is complaining about. There's definitely more reason to use it than just "efficiency gain", which is why many languages introduced in the last decade have it built in (e.g. Rust, Scala or Swift).
- mcphage 9y ago> The sum type, which the author is talking about, is not the same as "discriminated union" pattern, the latter being the crude implementation of the former. Could you say something about the difference between the two? I'm not aware what it is. Edit: wow I accidentally a word.
- mrkgnao 9y agoIIRC discriminated unions are plain C(++) unions with an added type tag, like at the beginning of the article. Brittle, prone to breakage when refactoring, etc. when compared to real sum types.
- Koshkin 9y agoActually, the article says, "A sum type, also called a discriminated union..."
- Wilduck 9y agoI'm really curious, I write a lot of python, and find myself wishing for sum types all the time. How do you see inheritance filling the same space? I'd love to be able to do something like: data Choices = Good | Bad | Ugly like I can do in haskell, where a value of type `Choices` can only ever be one of those options. But there doesn't seem to be any reasonable approximation in python.
- Ded7xSEoPKYNsDd 9y agoThe OOP pattern dfox is referring to would look something like this: class AbstractChoice: # defines all common operations on choices # plus potentially some useful stuff on top of those pass class Good(AbstractChoice): # conatins the code specific to good things pass class Bad(AbstractChoice): pass class Ugly(AbstractChoice): pass This isn't a straight-on replacement though. It's especially bad when you want to separate your concerns not along the good-bad-ugly-axis but something different (which is when you'd e.g. go on to use mixins, or that ugly visitor pattern we've seen in the OP).