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

Hide processing time from the user

What happens in a regular old web application when a user makes a request? This web application could be built in Drupal or Ruby on Rails or Django. These frameworks all, on a very general level, share some characteristics — and not just... Continue →