Favor early returns over short-circuits

Short circuit conditions are some neat syntactic sugar.

return team.HasCaptain && team.HasTrainer && sponsor.CanSupport(team);

Well OK, that code is not immediately obvious. We’re not gonna be a byte white knight – instead we’ll make it super obvious by putting conditions on their own lines:

return team.HasCaptain
    && team.HasTrainer
    && sponsor.CanSupport(team);

I have no quarrel with the readability of this code. However, with this obvious code, I don’t see much of an advantage over using explicit early returns:

if(!team.HasCaptian) return false;
if(!team.HasTrainer) return false;
if(!sponsor.CanSupport(team)) return false;
return true;

Focus on the future

The advantage of early return lies in debugging. Where the short-circuited condition counts as one line, the early return version has 4 autonomous lines where you can put break points or insert a logging command.

When you come back to read this code later, both options are easy to understand. It’s just that chances are that you came back to find a bug – and in that case one of the options is superior.

Next Article: Same Line Or Bracket