The war on if-else - The evil else if - part 2
TL;DR More rants from my campaign to rid the world of bad code, one if statement at a time.
IMHO else-if is a code smell, you might disagree, but before you dismiss this as the ramblings of a madman, take a look at the code below.
All righty, here is why…. The problem with else-if,
- You simply don’t need it.
- Once you start adding else-if it can be hard to stop.
- The more you add the worst it gets.
- It leads to the darkside 😀
When it comes to clean code, I try to have just one condition per function, yes that’s right, just one. If you have more than that you need a case or switch statement ( depending on your language ). Or even better a lookup decision table.
But first let’s have a look at the evil that is else-if.
Example One
For the first example it’s simple enough, and I’ve seen plenty of developers do this, the else-if is totally redundant, but you would be surprised at how many people actually still do this.
function for_the_love_of_code_get_that_else_if_out_of_your_head(){
boolean condition = false;
// Bad Code, else if is totally redundant
if (condition) {
jump();
} else if (!condition) {
run();
}
// Better, nice and simple, you got it
if (condition) {
jump();
} else {
run();
}
}
Example Two
This is just a mess of spagetti, this could be a lot better, I’ve added a new code-smell can you see it. Hint: magic numbers
void just_so_smelly(){
// Bad Code why I never use if else reason 2
int value = 1;
if (value == 1) {
jump();
} else if (value == 2) {
run();
}
// Better
switch (value) {
case 1:jump();break;
case 2:run();break;
}
}