Versions Compared

Key

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

...

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

This guideline demonstrates how conflicts can arise between the above two statements These two requirements can be counter intuitive when expressions contain side-effects. This is because, such expressions follow the left to right evaluation order irrespective of operator precedence, associativity rules and indicative parentheses.

Noncompliant Code Example

This noncompliant 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 levels. 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 a non-zero factor when the user is authorized and a zero value, when not.

In this case, the programmer expects the rightmost subexpression to evaluate first because of the greater precedence of the operator '*' than the operator '+'. The parentheses reinforce this belief. These ideas lead to the incorrect conclusion that the right hand side will evaluate evaluates 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 is below the threshold of 10 (expecting number = 0, due to because of number=get()). Ironically, the program grants access to the unauthorized user. The reason is that evaluation of 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 parentheses.

...

While diligently following the left to right evaluation order, a programmer can expect this compliant code solution to evaluate to an expected final outcome depending on the value returned by the get() method.

...

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 because operands are evaluated in place first, and then subject to laws of operator precedence and associativity.

Risk Assessment

Side-effects in expressions can be misleading due to their evaluation order. Failing to keep in mind the order in mind evaluation order of expressions containing side effects can result in unexpected output.

...