if/else -> if-return

You want to write readable code. Readable code has short functions and is easy to get an overview of. Being able to follow a single path of execution until the end before starting the next is easier than having multiple possible paths in mind.

if/else is a very common occurrence in code. It can look something like this:

if(expiryDate) {
    doSomething(expiryDate);
}
else {
    doSomethingElse();
}

This adds two different paths that must be understood mentally: okay, either we do something with the expiry date, or we do something else. These are two statements that must be evaluated for their sanity together rather than one at a time.

Of course, it gets much worse: many nested if/else statements are much longer and more complex.

As an alternative, I would recommend using if-return:

if(expiryDate) {
    return doSomething(expiryDate);
}
doSomethingElse();

The advantage of using this version of the code is that reading requires only keeping one path of execution in mind. Okay, if an expiry date is given, we do something. Fine. Otherwise, we do something else. Also fine.

Of course, the change cannot always be made so easily. If the code is part of a longer code block, you might have to extract it.

Changing if/else to if-return whenever possible in our code base has taken a common source of complexity and removed it almost entirely.

 
9
Kudos
 
9
Kudos

Now read this

Three Thoughts on Amazon Go

Amazon just released a video explaining the concept for a new kind of grocery store, with no queues and no cashiers and no waiting. Here are three thoughts on the implications of the technology and concept. The idea behind the store... Continue →