Functional Programming – Why Discriminate Unions are Associated

functional programming

In many years of OO programming I've understood what discriminated unions are, but I never really missed them. I've recently been doing some functional programming in C# and now I find I keep wishing I had them. This is baffling me because on the face of it, the concept of discriminated unions seems quite independent of the functional/OO dichotomy.

Is there something inherent in functional programming that makes discriminated unions more useful than they would be in OO, or is it that by forcing myself to analyse the problem in a "better" way, I've simply upped my standards and now demand a better model?

Best Answer

Discriminated unions really shines in conjunction with pattern-matching, where you select different behavior depending on the cases. But this pattern is fundamentally antithetical to pure OO principles.

In pure OO, differences in behavior should be defined by the types (objects) themselves and encapsulated. So the equivalence to pattern matching would be to call a single method on the object itself, which is then overloaded by the sub-types in question to define different behavior. Inspecting the type of an object from the outside (which is what pattern matching does) is considered an antipattern.

The fundamental difference is that data and behavior is separate in functional programming, while data and behavior are encapsulated together in OO.

This is the historical reason. A language like C# is developing from a classic OO language to multi-paradigm language by incorporating more and more function features.

Related Topic