Note | ||
---|---|---|
| ||
This rule may be deprecated and replaced by a similar guideline. 06/28/2014 -- Version 1.0 |
According to The According to the Java Language Specification (JLS), §15.7, "Evaluation Order" [JLS 2015]:
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" of the Java Language Specification adds:
Java programming language implementations must respect the order of evaluation as indicated explicitly by parentheses and implicitly by operator precedence.
These When an expression contains side effects, these two requirements can be counter-intuitive when expressions contain side effectsyield 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 are forbidden to must not write to memory that they subsequently read , and are also forbidden to must not write to any memory twice. Note that memory writing reads and reading writes can occur either directly in the expression from assignments or indirectly through side effects in functions 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 different threshold levelsthresholds. Each user has a rating that must be above the threshold to be granted access. As shown, a simple function can calculate the rating. The get()
method is expected to return a non-zero factor value for authorized users who are authorized, and a zero value for those who are unauthorized users.
In this case, the programmer expects the rightmost subexpression to evaluate The programmer in this example incorrectly assumes that the rightmost subexpression is evaluated first because the *
operator has a higher precedence than the +
operator . The parentheses reinforce this belief. These ideas lead and because the subexpression is parenthesized. This assumption leads to the incorrect conclusion that the right hand side evaluates to zero whenever the get()
method returns zero. The programmer expects number
to be 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 rating 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.
Code Block | ||
---|---|---|
| ||
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; // Assign number to non zerononzero 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.
Code Block | |||
---|---|---|---|
| |||
int number = 17; number = ((31 * ++number) * (number=get())) + (number > threshold[0] ? 0 : -2); |
Compliant Solution (Order of Evaluation)
This compliant solution uses equivalent code with no side effects . It performs only one write, to number
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 | ||
---|---|---|
| ||
int number = 17; final int authnum = get(); number = ((31 * (number + 1)) * authnum) + (authnum > threshold[0] ? 0 : -2); |
Exceptions
EXP08EXP05-J-EX0: The postfix increment and postfix decrement operators (++)
and (--)
read a numeric variable, and then assign a new value to a the variable and then subsequently read it. These are . Although these operators read and modify a value, they are well-understood and are an exception to the rule against reading memory that was written in the same expression.this rule. This exception does not apply if a value modified by an increment or decrement operator is subsequently read or written.
EXP05-JEXP08-EX1: The logical operators conditional-or ||
and conditional-and &&
operators have well-understood short-circuit semantics, so expressions involving these operators may violate this rulesemantics. 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 | ||
---|---|---|
| ||
public void exampleFunction(){ exampleMethod(InputStream in;) { int i; // SkipProcess onechars char,until process'' nextfound while ((i = in.read()) != -1 && i != '\'' && (i = in.read()) != -1 && i != '\'') { // ... } } |
Although the overall conditional expression violates this rule, this code is compliant because the sub-expressions on either side of the &&
operator do not violate it. Each has exactly 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 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 also multiple operator precedence levels is straightforward. Determining the correctness of such uses is infeasible in the general case; heuristic warnings could be useful.
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Parasoft Jtest |
| CERT.EXP05.CID | Avoid using increment or decrement operators in nested expressions | ||||||
PVS-Studio |
| V6044 | |||||||
SonarQube |
| S881 | Increment (++) and decrement (--) operators should not be used in a method call or mixed with other operators in an expression |
Related Guidelines
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="3bb0ffca-a70b-4253-962c-d1ab574dcd5c"><ac:plain-text-body><![CDATA[
http://www.aitcnet.org/isai/]
Side Effects and Order of Evaluation [SAM |
] |
Bibliography
...
[JLS |
AA. Bibliography#JLS 05]]
2015] |
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.7]
...
EXP04-J. Do not perform assignments in conditional statements 02. Expressions (EXP) EXP06-J. Do not use expressions with side effects in assertions