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

I wouldn’t recommend process

Back in February 2015 (a year ago!) I wrote that I wouldn’t recommend Scrum. Looking back I see that I was merely grasping at the end of a bigger concept. Here I will try to clarify and generalize from the original post. I would like to... Continue →