You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 112 Next »

According to the JLS, §15.7, "Evaluation Order" [JLS 2005]:

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

§15.7.3, "Evaluation Respects Parentheses and Precedence" adds:

Java programming language implementations must respect the order of evaluation as indicated explicitly by parentheses and implicitly by operator precedence.

When an expression contains side effects, these two requirements can yield unexpected results. Evaluation of the operands proceeds left to right, without regard to operator precedence rules and indicative parentheses; evaluation of the operators, however, obeys precedence rules and parentheses.

Expressions must not write to memory that they subsequently read and also must not write to any memory twice. Note that memory reads and writes can occur either directly in the expression from assignments or indirectly through side effects in methods called in the expression.

Noncompliant Code Example (Order of Evaluation)

This noncompliant code example shows how side effects in expressions can lead to unanticipated outcomes. The programmer intends to write access control logic based on thresholds. Each user has a rating that must be above the threshold to be granted access. The get() method is expected to return a non-zero value for authorized users and a zero value for unauthorized users.

The programmer in this example incorrectly assumes that the rightmost subexpression is evaluated first because the * operator has a higher precedence than the + operator and because the subexpression is parenthesized. This leads to the incorrect conclusion that number is assigned 0 because of the rightmost number = get() subexpression. Consequently, the test in the left-hand subexpression is expected to reject the unprivileged user because the value of number is below the threshold of 10.

However, the program grants access to the unauthorized user because evaluation of the side-effect-infested subexpressions follows the left-to-right ordering rule.

class BadPrecedence {
  public static void main(String[] args) {
    int number = 17;
    int threshold = 10;
    number = (number > threshold ? 0 : -2) 
             + ((31 * ++number) * (number = get()));
    // ... 
    if (number == 0) {
      System.out.println("Access granted");
    } else {
      System.out.println("Denied access"); // number = -2
    }
  }

  public static int get() {
    int number = 0;
    // Assign number to non zero value if authorized else 0
    return number;
  }
}

Noncompliant Code Example (Order of Evaluation)

This noncompliant code example reorders the previous expression so that the left-to-right evaluation order of the operands corresponds with the programmer's intent.

Although this code performs as expected, it still represents poor practice by writing to number three times in a single expression.

number = ((31 * ++number) * (number=get())) + (number > threshold ? 0 : -2);

Compliant Solution (Order of Evaluation)

This compliant solution uses equivalent code with no side effects and performs not more than one write per expression. The resulting expression can be reordered without concern for the evaluation order of the component expressions, making the code easier to understand and maintain.

final int authnum = get();
number = ((31 * (number + 1)) * authnum) + (authnum > threshold ? 0 : -2);

Exceptions

EXP05-EX0: The increment and decrement operators (++) and (--) read a numeric variable, and then assign a new value to the variable. While these operators read and modify a value, they are well-understood and are an exception to this rule. This exception does not apply if a value modified an increment or decrement operator is subsequently read or written.

EXP05-EX1: The logical operators || and && have well-understood short-circuit semantics.  Writes followed by subsequent writes or reads does not violate this rule if they occur in different subexpressions of || or &&.  Consider the following code example:

public void exampleMethod(InputStream in) {
  int i;
  // Process chars until '' found
  while ((i = in.read()) != -1 && i != '\'' && 
         (i = in.read()) != -1 && i != '\'') {
    // ...
  }

}

The controlling expression of the while loop does not violate this rule because the subexpressions on either side of the && operators do not violate it. The first and third subexpressions have exactly one assignment and one side effect (the reading of a character from in).

Risk Assessment

Failure to understand the evaluation order of expressions containing side effects can result in unexpected output.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP05-J

low

unlikely

medium

P2

L3

Automated Detection

Detection of all expressions involving both side effects and multiple operator precedence levels is straightforward. Determining the correctness of such uses is infeasible in the general case; heuristic warnings could be useful.

ToolVersionCheckerDescription
SonarQube Plugin2.4S881 

 

Related Guidelines

Bibliography

 

      02. Expressions (EXP)      

  • No labels