Short Circuit Logic

This year, I came across code like the following several times – in different projects, written by different developers (yellow indicates the piece of code I’m wondering about). I’m not sure why they do it – maybe they come from a programming language that doesn’t know about short circuit logic.

If you think „what the heck is short circuit logic“, please read on.

01SampleCode

To get you started, ask yourself what the output of the above code will be.

The answer is: Only the error message „A is not ok“ will be given to the user.

The reason for this is that in the second if-statement, short circuit logic will apply:
ret already evaluates to false, so the outcome of the && operation will always be false, no matter what the second operator will yield. And therefore, the second operator will not even be evaluated (the code won’t be executed). In our case this means that the second info message to the user will not be shown.

There are valid constructions where the above ret = ret && x makes perfect sense, f.ex. if the second Operator is an expensive validation itself.

The other very common shortcut is: a || b – if a evaluates to true, b won’t be evaluated.

Read more here: http://en.wikipedia.org/wiki/Short-circuit_evaluation

PS: No, I don’t want to argue about the following:

  • Why worry? Only the first error message is of interest to the user. I’d respond that in that case, we should exit the method after the first failed criterium.
  • It’s only a warning text that’s not shown – why bother? Because it’s a lot easier for the user to fix several errors at once. And the developer had that in mind, too, otherwise they would have constructed the code differently.