Danger with any Method

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

Any method that returns any type of value can be used in a boolean expression, so side-effects are a concern.

Danger with any Method

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 ;  

QUESTION 4:

Would it be useful to have a non-short-circuit AND operator?