I recently discovered that Java (and Scala) include non-short-circuiting logical operators &
, |
, and ^
. I previously thought thes
Hmm. I know they can be incredibly useful for optimizing C/C++ code if used carefully. It might apply to Java as well.
The major use in C -- other than actual bit operations -- is to remove a pipeline stall. The short circuit operators require a branch operation. The bitwise operator will compute both sides and removes the chance for a mispredicted branch and the resulting stall.
Using the non-short-circuit boolean operators implies that the operands have side effects. If they had no side effects, then the programmer could have used the short-circuit versions with no change in functionality.
In code written in a functional style (which Scala surely encourages but does not require), side effects are an indication that something unusual is going on. Unusual things should be clearly indicated in code, rather than by something as subtle as a non-short-circuit boolean operator.
They're useful if the right-hand side is a function with side-effects that you want to execute regardless (e.g. logging). However, I would suggest that that's a bit of a code smell and will certainly be unintuitive to the next guy.
If you are trying to track answers or input for something, and that depends on both sides of your non-short-circuit boolean running.
As an example, say you have:
if(methodA() & methodB()){
//some code
}
And within the methodB() method some essential code is running. If that was a short circuit code ( && ) and methodA() was false, methodB() would never run.
That is one of the uses I can think of, at least.