I recently discovered that Java (and Scala) include non-short-circuiting logical operators &, |, and ^. I previously thought these only worked as bitwise operators. While maybe there is an argument for ^, I can't think of very good reasons for using non-short-circuiting logical operators--although sure, I can contrive an example.

Are these operators useful? They seem more likely to cause hard-to-catch bugs.

No, the bitwise operators should only be used for bitwise operations, IMHO :)
–
Niklas B.Mar 2 '12 at 21:41

1

The only possible answers to this question are specific examples of "non-short-circuiting operators are useful when you don't want short circuiting". So the real question is "when do you not want short circuiting"?
–
Dan BurtonMar 2 '12 at 22:48

4 Answers
4

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.

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.

When I was writing Guava's com.google.common.math, when the second condition was particularly fast, my benchmarks sometimes indicated that non-short-circuiting operators were faster than short-circuiting operators for this reason. (That said, I wouldn't have made that change if I didn't have very solid, detailed benchmarks.)
–
Louis WassermanMar 2 '12 at 23:10

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.