August 8, 2016
Every young developer gets to know the most common rules in programming quickly, either by their own research or by code review comments. Write small classes and small methods/functions. Be SOLID, Don't Repeat Yourself, Keep It Simple Stupid and a lot of other programming principles.
Today I would like to propose another way - one that may be a bit controversial in principle; let's call it - DNIE (read as deny) unrolled to Do Not If Else.
If's are often considered harmful. They are the source of evil and sometimes bugs. But the worst thing is that they hide abstractions.
Before we go further, I have to make an important disclaimer - I don't want to say never ever use if or anything like that. There are cases when an
if statement is the easiest, the cleanest and the most appropriate solution for a problem. E.g. I cannot imagine implementing most sorting algorithms without such construction. Unfortunately
if's are overused and often makes software harder to maintain.
The very first question that you should ask yourself when you use
if is: why do I need it? And extract the whole statement to the method named as an answer. Now it's time to go deeper.
Need a different value for a different case? You probably need some polymorphism. Protecting against
null? Use a guest object. Handling many scenarios? Just register them and run a callback for a specific one. Is something bad happening in many different places? Maybe introduce something higher to follow the flow?
The key is that
if shouldn't handle business rules, but should be replaced by proper abstractions which would improve understanding of the ideas behind the code. You should take some help from well known patterns and, thanks to them, improve the readability of the code. As a drawback, sometimes you have to write more code compared to a
if-else, but there is a high chance that you won't regret this when requirements change (and they will change!) or you need to introduce a new feature.
Should I also mention that code without
if's is much easier to test and debug?
And here comes the best part - as a side effect of the DNIE principle you will learn how to use patterns in practice and - what is more important - you will learn how to structure and organize your code. You will be forced to create stable architecture for complex problems where everything is precisely named and defined; essentially, where everything is as simple as possible.
Finally, you will become a better programmer.
As a starting point I would recommend reading refactoring tricks about how to simplify or completely replace
if statements on source making.