Programming – When Is Short-Circuit Evaluation Bad?

booleancomputation-expressionsterminology

To be a bit more clear, I'll state that I've spent lots of time with different languages. But until now it's been either it'll use it all the time or it doesn't support it at all.

Now work has me starting on projects that require VB.net and I see it provides it both ways in terms of AND and ANDALSO. The first one does not short circuit, and the 2nd one does.

So this leads me to wonder why? As having it setup like this seems to imply that it would come up quite often that one would want to switch modes. But I can't think of any situations where it would be a bad thing to use Short Circuit.

I know this could very well get into more of an option thing, so if I need to put this at some place else just tell me where.

Though I'm hoping there is at least an official answer, as to why having both options would be better then always doing Short Circuit, when it's available.

Best Answer

Some terms in a logical expression can have side effects. It is sometimes necessary to ensure all side effects happen in the stated order, and none are skipped and it is the evaluation result that guides the logic:

if not (PushAirPlane(thrust) and TurnAirplane(vector)), SimulateCrash(severity)

In other cases, you don't want to evaluate any of the remaining terms if an earlier evaluation returns false.

if IsAirborne() and not (PushAirPlane(thrust) and TurnAirplane(vector)), SimulateCrash(severity)

Some will/have argued that relying on the short-circuit behavior in the second example is bad form, but that's getting into coding style and belief systems. There are many very good bits of code in the world that do rely on nearly every feature a language provides, and that's just the way it is.

VB's ANDALSO is crisp and seems to be an attempt to make the practice more acceptable.

As JimmyJames points out in his answer, there can be measurable performance implications around short-circuit evaluation. Languages that do not provide the mechanism, always evaluate every term of the expression, while those that do provide it, can generate extra branch statements. Either way, much depends on the number of processing steps required to evaluate each of the terms and also on compiler and CPU architectures. You would normally not care about such things until you have a measured bottleneck in the code and need to work out how to alleviate it. Any do or don't rules regarding allowing short-circuit evaluation in your code would have roughly equal chance of causing slower code and optimizing early can be a total waste of time, so always measure, then optimize.

Related Topic