Is it ever a good coding style to heavily rely on short-circuit in boolean evaluation?
I've known someone who loves to do this. For instance, if the business logic is "If Alice is not hungry OR if both Alice and Bob are hungry", instead of writing
// if Alice is not hungry or both alice and bob are hungry
if (!A || A && B)`
he would write
// if Alice is not hungry OR both alice and bob are hungry
if (!A || B)
arguing that ||
is short-circuited, so the right-operand is evaluated if and only if the first one is false
(which means A = true
).
(The annoying thing about this is that at first glance, you would think this is a bug but then feel you would look stupid if you change it to what is more obvious!)
Short-Circuit Evaluation: Short-circuiting is a programming concept in which the compiler skips the execution or evaluation of some sub-expressions in a logical expression. The compiler stops evaluating the further sub-expressions as soon as the value of the expression is determined.
Disadvantage 1: Any logic which was expected to be executed as part of the conditions which are bypassed will not be executed. I.e. say we have Condition-1 OR Condition-2 where condition-1 is evaluated to TRUE.
So when Java finds the value on the left side of an || operator to be true, then Java declares the entire expression to be true. Java's && and || operators use short circuit evaluation.
AND(&&) short circuit:If there is an expression with &&(logical AND), and the first operand itself is false, then a short circuit occurs, the further expression is not evaluated, and false is returned.
You certainly can and should rely on short circuiting in expressions, but the example you give is just bad programming. The logic of the expression should match the comment and the human-readable logic of the test. The optimizer fully understands boolean logic and will optimize away any apparent inefficiency that your teammate might complain about.
The most important thing is to make the code clear and understandable for the developer. Writing clever code to prove how clever you are is never a good practice.
Is it ever a good style? Yes, I think most people can appreciate this idiomatic style:
myFoo != null && myFoo.myMethod();
This doesn't really have anything to do with short-circuiting; those two expressions would be equivalent even without short-circuiting:
A B !A | A & B !A | B ----------------------------------- 0 0 1 1 0 1 1 1 1 0 0 0 1 1 1 1
Just pick whichever you think will be easier to understand and manage in the future; whichever more explicitly conveys your purpose. The clear winner in this regard seems to be your first snippet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With