My favorites design patterns - Builder
Recently, I was trying to handle errors in the programming language I’m developping. Nothing fancy here and the problem was quickly solved with a simple:
- Lack of genericity: Each time I expected or got a different token, I needed to change the text in the message.
- Lack of testability: I basically wanted to be able to check if the error type and the error message were the same. But then if I have a stupid typo then my test fail.
So at that point, I decided to make the solution more generic and more testable. Basically, I wanted something roughly like:
And here comes the Builder pattern. The idea is that we could build an object by changing the variables in an expressive way. So finally, I came up with this:
That you would use like:
A much shorter, expressive and typo incensitive solution !