I write about things that I like and things that I don’t, mainly in the business, art and tech spher
If-else keyword built into nearly every programming language and simple conditional logic are easy for anyone to understand. If you are a programmer, you know else keyword. But if you are a good programmer, don’t use this keyword. One of the biggest mistakes I fell into when starting was overusing the else keyword when writing conditionals. I stopped using this keyword in my programs since 5 years ago. Let me explain!
Think about what else means, it means “if A then this, if not A then that;”. This isn’t a problem if A is binary — the problem space is only 2 cases. But if A is a combination of binary variables, or contains larger variables, your negative problem space can be unexpectedly large and difficult to understand, test and maintain.
To avoid if/else if, to only use if statements, to spend the time to ensure the entry criteria for your group of if’s are mutually exclusive so that the answers don’t depend on the order of execution.
Our example is a traffic light (i.e. TrafficLight object) with 3 different states: Red, Yellow and Green, each with its own set of rules. The rules go like this:
Don't use if-else keyword
The simple way
We only remove else keywords and re-write all conditions.
Or we can use a switch instead of if-else. A switch looks much cleaner when you have to combine cases. A if-elsewill quickly get out of control.
A switch statement might prove to be faster than if-else provided a number of cases are good.
The style conventions are.
We can use the State Pattern to remove all if-else keyword in these codes
Here, we introduce lots of if-else blocks/switch statements to guard the various conditions. The state pattern¹ fits in such a context. It allows your objects to behave differently based on the current state, and you can define state-specific behaviors. In this pattern, we start thinking in terms of possible states of our traffic light, and you segregate the code accordingly.
Traffic Light: Green (1 minute) → Yellow (10 seconds)→ Red (1 minute)
They are print the same output as following.
It is these examples of bad codes and good codes. Finally, thanks for reading and hopefully I’ve covered everything.