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!
I’m an AWS Serverless Hero and the author of Production-Ready Serverless. I have run production workload at scale in AWS for nearly 10 years and I have been an architect or principal engineer with a variety of industries ranging from banking, e-commerce, sports streaming to mobile gaming. I currently work as an independent consultant focused on AWS and serverless.
Here is a complete list of all my posts on serverless and AWS Lambda. In the meantime, here are a few of my most popular blog posts.
- Lambda optimization tip – enable HTTP keep-alive
- You are thinking about serverless costs all wrong
- Many faced threats to Serverless security
- We can do better than percentile latencies
- I’m afraid you’re thinking about AWS Lambda cold starts all wrong
- Yubl’s road to Serverless
- AWS Lambda – should you have few monolithic functions or many single-purposed functions?
- AWS Lambda – compare coldstart time with different languages, memory and code sizes
- Guys, we’re doing pagination wrong