November 16, 2014
Follow me on Twitter

The Case Against Else

Brent Simmons builds the case against else – specifically, the awkwardness of commenting out the else{} clause without fouling up your brackets.

There’s a deeper case we should mention: radical simplification of conditionals. In the old days, nested conditionals were a dime a dozen, and we all learned to build (and debug) trees of if statements nested three our four deep.

We don’t do that anymore.

In fact, lots of people argue that a conditional is too complex if (a) either clause has more than one line, or (b) it has an else{} clause at all. Instead of an else clause:

if(mill()) { 
 drill); } 
else { 
 fill(); }  

we now write a guard:

if (mill()) {
 return; }

Or, if you should never drill if milling fails, move the test to drill()

bool drill() {
 if (!mill()) return false;
 return true;

And now you’ve got a simpler guard:

if (!drill()) return;

In this view, else is a mild code smell.