Put the fastest method
first because if it returns a false you are done immediately.
You don't need to run the method that takes hours.
if ( methodThatWorksInstantly() && methodThatTakesHoursToRun() ) doSomething()
If the first method returns false, the
second method is not evaluated at all,
saving time.
The result of evaluating the boolean expression is
false
whenever methodThatWorksInstantly() is
false.
Only when it is true is the time consuming method executed.
Danger: This trick works correctly only if the skipped method
does nothing permanent.
In other words, short-circuit evaluation is safe when
the skipped method does nothing but
compute true or false.
Short-circuit evaluation is not safe when the
skipped does more than that.
For example:
boolean methodThatTakesHoursToRun()
{
// make a permanent change to the state of
// an object that the rest of the program uses.
// now return a true or false
}
When a method makes
permanent changes to data,
it must be called regardless of
the true/false value of other parts of the Boolean expression.
Otherwise, a computation that might be important to the program might be skipped.
When a method makes a permanent change to data
the method is said to have a side effect.
When methods have side effects,
you must be careful when using a short-circuit
operator.
(Thought question: ) Do you have to worry about side effects with
methods that return int?
Click here for a