When you consider the age old problem of representing different shapes (circle, triangle, square, rectangle, etc.) my OO fed developer brain naturally jumps to a class hierarchy along the line of:
This is perfectly fine and legit, but it’s not the only way to approach things. Since I’ve been on a more varied diet of programming paradigms I’m much more open to the idea of using F#’s discriminated unions to represent hierarchical data.
Discriminated union is a fundamental type in function programming, and for C# developers, think of it as an Enum with strongly typed names where the names don’t have to be of the same type. Using discriminated unions, you can rewrite the above code as:
And to test it, let’s create some shapes and workout their respective areas:
Was that more difficult than its C# counterpart? Not at all, in fact, I’ve littered the F# code with comments and still ended up with near half as much code! Check out my solution for project euler problem 54, a working poker hand evaluator in 100 lines of code , pretty sweet
That said, class hierarchies are great at modelling real world entities and they allow you to capture commonalities and shared behaviours, if done correctly they can remove duplicated code and reduce defects.
Discriminated unions on the other hand, are a great fit for hierarchical data structures such as binary tree, and for small hierarchies it requires little overhead in setting them up so it can give you a nice productivity boost.
Whilst I’m not suggesting that you should start converting all your class hierarchies to discriminated unions, I think there is a lot of value in having it in your toolbox nonetheless. The more tools you have at your disposal the better, being able to use the right tool for the right task beats hammering a screw in my opinion!
4 thoughts on “F# – Use Discriminated Unions instead of class hierarchies”
I think the key to choosing correctly between class hierarchies and unions is extendability by outsiders. If you want to allow that without forcing them to modify your code, then class hierarchies are the way to go.
Unions are attractive when used in conjunction with pattern matching, as the compiler tells you if all cases are handled.
It’s also easy to add new cases to a union, no ceremony involved. With classes, one often finds oneself shoe-horning new subclasses into interfaces that are seldom exactly what you would like them to be.
Pingback: F# – Enums vs Discriminated Unions | theburningmonk.com
Pingback: F# – Serializing F# Record and Discriminated Union types | theburningmonk.com
Pingback: Here Be Monsters – Message broker that links all things | theburningmonk.com