Practical programming advice
Replacing If-Else and Switch With Parametric Polymorphism
Having more classes does not equal higher complexity.
So, there is a good chance that you’ve used parametric polymorphism already — it’s basically just generics. But, do you know how generics can help you reduce the use of branching statements, such as if-else
and other control-flow statements?
if-else
is often a poor choice, especially if you want to follow the Open-Closed principle, making your application easily extensible. We’ll get into why this is, in the following section. (I have a list of articles on this subject as well)
Back as a junior developer, I’d often resort to traditional branching techniques, plastering if-else
and switch
statements all over the place.
And, I get why you’re likely doing it as well. It’s the easy thing to do. It doesn’t require you to think hard about design and interactions. All possible paths are immediately visible to you, so you don’t have to dig thru layers of abstraction and track down implementations.
But…
Control flow statements are deceivingly simple, and you pay a high price for it, later.