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.

 
5
Kudos
 
5
Kudos

Now read this

Workspace Ownership

Although offices are almost always legally owned by a company, making the employees feel ownership comes with a lot of benefits. If employees feel at home in the office they are more likely to share ideas and less likely to hold back... Continue →