Any function 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 maximum; // set by computeMaximum()
. . .
if ( sum < 100 && computeMaximum() < 500 )
{
result = 2 * maximum ; // maximum might not be computed.
}
. . .
There is a problem here.
The method that follows &&
sets maximum
(as a side effect)
only when
sum is greater than 100.
The assignment statement will sometimes put
the wrong value in result.
You should arrange the expression like this:
int maximum;
. . .
if ( computeMaximum() < 500 && sum < 100 )
{
result = 2 * maximum ;
}
. . .
With this arrangement the side effect 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 maximum;
. . .
maximum = computeMaximum();
if ( maximum < 500 && sum < 100 )
{
result = 2 * maximum ;
}
. . .