Short-Circuiting


The && and || logical operators just shown are known as short-circuited logical operators. When the Java VM executes an expression using a short-circuited logical operator, it evaluates the left operand (the expression to the left of the operator) of the expression first. The result of the left operand may immediately determine the result of the entire expression.

In the case of or (||), if the left operand is true, there is no need to evaluate the right operand. The entire expression will always be true. The Java VM saves time by executing only half of the expression. With respect to and (&&), if the left operand is false, the entire expression will always be false. The Java VM will not evaluate the right operand.

You may have a rare need to always execute both sides of the expression. The code on the right-hand side may do something that you need to always happen. This is poor design. Lesson 4 points out that methods should either effect actions or return information, but not both. Likewise, operands should be viewed as atomic operations that are either commands or queries. You should be able to restructure the code so that the action occurs before executing the complex conditional.

If you still feel compelled to always execute both operands, you can use non-short-circuited logical operators. The non-short-circuited and operator is a single ampersand (&). The non-short-circuited or operator is a single pipe (|).

Note that xor (^) is always non-short-circuited. Java cannot discern the result of an xor expression from only one operand. Refer to the TDTT above to see why.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net