Any method that returns any type of value can be used in a boolean expression, so side-effects are a concern.
For example,
say that a method computeMaximum()
computes the maximum value of some variables,
stores the result in maximum and returns
that value:
int sum; int maximum; // set by computeMaximum() . . . if ( sum < 100 && computeMaximum() < 500 ) // maximum might not be computed. { . . . } result = 2 * maximum ;
There is a problem here.
The method that follows &&
sets maximum
(as a side effect)
only when
sum is less than 100.
The assignment statement will sometimes put
the wrong value in result.
You should arrange the expression like this:
int sum;
int maximum;
. . .
if ( computeMaximum() < 500 && sum < 100 )
{
. . .
}
result = 2 * maximum ;
With this arrangement the side effect of
computeMaximum() will always happen.
The two if statements look almost identical;
however, the first one is a bug (probably).
Bugs like this can be hard to find.
The best solution is to write computeMaximum()
so that it has no side effect,
then use it like this:
int sum;
int maximum;
. . .
maximum = computeMaximum();
if ( maximum < 500 && sum < 100 )
{
. . .
}
result = 2 * maximum ;
Would it be useful to have a non-short-circuit AND operator?