0

Should I leave the else clause in a case like this where the compiler marks the else as redundant code and the else makes the code appear more logical --> better readable?

if (aCondition){
    doStuff();
    return someMethodResult();
}
else {
    doOtherStuff();
    return someOtherMethodResult();
}

or

if (aCondition){
    doStuff();
    return someMethodResult();
}
doOtherStuff();
return someOtherMethodResult();`
3
  • Also see here.
    – doubleYou
    Feb 15, 2018 at 22:39
  • @PhilipKendall fixed Feb 15, 2018 at 22:52
  • 3
    Better readable here is a matter of taste. Feb 15, 2018 at 23:06

2 Answers 2

5

It depends on the semantics of aCondition.

My guiding line is that the standard / normal path of execution should stay on the top nesting level, and conditional paths should be found on deeper nesting levels.

If aCondition checks for some special case, the return someMethodResult(); is an early return, and the remaining code is the normal path of execution. Here I prefer the second approach (just making sure the return statement is well visible, as you did), as here the normal path of execution stays on the top nesting level.

If its just two different cases, I'd use the redundant else, because here both paths are conditional, none of them can be called normal. So in this case I like having both indented.

1

As for redundant elses after returns: It depends. What looks "most familiar" is probably the most readable. Follow the style used in typical existing code in your language.

In typical C / Java code, many would leave off the redundant else. (I'd tend to leave it, YMMV)

But, in asynchronous / callbacky JavaScript code, like node.js, it is fairly common practice to put "return" everywhere, e.g.

return callback(err, result);

where the "return" is not to actually return a value, but to prevent fall through.

Also, with Promises, you need to put return most everywhere :-), so as to return the Promise.

In this style of code, your eyes often "gloss over" the return, so the redundant else is very useful.

Not the answer you're looking for? Browse other questions tagged or ask your own question.