Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Note
titleDeprecated

This rule may be deprecated and replaced by a similar guideline.

06/28/2014 -- Version 1.0

 According to The Java Language Specification (JLS), §15.7, "Evaluation Order" [JLS 2015] Wiki MarkupAccording to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\] section 15.7 "Evaluation Order":

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

Section 15§15.7.3, "Evaluation Respects Parentheses and Precedence", on the other hand states 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 expressionThis guideline demonstrates how conflicts can arise between the above two statements when expressions contain side-effects.

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 some access control logic based on different threshold levelsthresholds. Each user has a rating that must be above the threshold , in order to be granted appropriate access. As shown, a simple function is used to calculate the rating. The get() method has been used to provide is expected to return a non-zero factor when the user is authorized value for authorized users and a zero value , when notfor unauthorized users.

In this case, the programmer expects that the rightmost subexpression would evaluate first because of the greater precedence of the operator '*' as compared to '+' or '>'. The parenthesis reinforce this belief. These ideas lead to the incorrect conclusion that the right hand side will evaluate to zero whenever the get() method returns zero. The test in the left hand subexpression should ideally reject the unprivileged user as the expected rating value 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 assumption 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 (= 0, due to number=get()). Ironically.

However, the program grants access to the unauthorized user . The reason is that because evaluation of the side-effect-infested subexpressions follows the left-to-right ordering rule and should not be confused with the tenets of operator precedence, associativity and indicative parenthesis.

Code Block
bgColor#FFcccc

class BadPrecedence {
  public static void main(String[] args) {
    int number = 17;
    int[] threshold = new int[20];
    threshold[0] = 10;
    number = (number > threshold[0] ? 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;
    // assignAssign number to nonnonzero zero value if authorized, else 0
    return number;
  }
}

Compliant Solution

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 expressionWhile diligently following the left to right evaluation order, a programmer can expect this compliant code to evaluate to an expected final outcome depending on the value returned by the get() method.

Code Block
bgColor#ccccff#ffcccc

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

Although this solution solves the problem, in general, it is advisable to avoid using expressions with more than one side-effect. It is also inadvisable to depend on the left-right ordering for evaluation of side-effects since operands are evaluated in place first, and then subject to laws of operator precedence and associativity.

Risk Assessment

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.

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

Exceptions

EXP05-J-EX0: The increment and decrement operators (++) and (--) read a numeric variable, and then assign a new value to the variable. Although 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 by an increment or decrement operator is subsequently read or written.

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

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

}

This rule is not violated by the controlling expression of the while loop because the rule is not violated by any operand to the conditional-and && operators. The subexpressions (i = in.read()) != -1 have 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 Side-effects in expressions can be misleading due to their evaluation order. Failing to keep the order in mind can result in unexpected output.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FLP03

EXP05-J

low

Low

unlikely

Unlikely

medium

Medium

P2

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] Section 15.7 "Evaluation Order" and 15.7.3 "Evaluation Respects Parentheses and Precedence"

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
Parasoft Jtest

Include Page
Parasoft_V
Parasoft_V

CERT.EXP05.CIDAvoid using increment or decrement operators in nested expressions
PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V6044
SonarQube
Include Page
SonarQube_V
SonarQube_V
S881Increment (++) and decrement (--) operators should not be used in a method call or mixed with other operators in an expression


Related Guidelines

Bibliography


...

Image Added Image Added Image AddedEXP05-J. Be careful about the wrapper class and autoboxing      02. Expressions (EXP)      02. Expressions (EXP)