If your API overflows with Boolean parameters, this is usually a bad smell.
Consider the following function call for example:
toContactInfoList(csv, true, true)
When looking at this snippet of code it is not very clear what kind of effect the two Boolean parameters will have exactly. In fact, we would probably be without a clue.
We have to inspect the documentation or at least the parameter names of the function declaration to get a better idea. But still, this doesn't solve all of our problems.
The more Boolean parameters there are, the easier it will be for the caller to mix them up. We have to be very careful.
Moreover, functions with Boolean parameters must have conditional logic like if
or case
statements inside. With a growing number of conditional statements, the number of possible execution paths will grow exponentially. It will become more difficult to reason about the implementation code.
Can we do better?
Sure we can. Lambdas and combinators come to the rescue and I'm going to show this with a simple example, a refactoring of the function from above.
This post is based on a great article by John A De Goes, Destroy All Ifs — A Perspective from Functional Programming.
I'm going to take John's ideas that he backed up with PureScript examples and present how the same thing can be elegantly achieved in Scala.