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.

 
8
Kudos
 
8
Kudos

Now read this

Stagnation and Tunnel Vision

It is easier to learn when you are young. So I have been told all my life. According to research on neuroplasticity the brain continues to grow and learn from what it is exposed to—it never stops. As we get older, life is filled with... Continue →