Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: text edits

...

This noncompliant example shows how side-effects in expressions can lead to unanticipated outcomes. The programmer intends to write access control logic based on different threshold levels. Each user has a rating that must be above the threshold to be granted access. As shown, a simple function is used to calculate the rating. The get() method is used to provide a non-zero factor when the user is authorized, and a zero value when the user is not authorized.

In this case, the programmer expects the rightmost subexpression to evaluate first because the * operator has a higher precedence than the + operator. The parentheses reinforce this belief. These ideas lead to the incorrect conclusion that the right hand side evaluates to zero whenever the get() method returns zero. Because the The programmer expects number = 0 due to to be 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 (number) is below the threshold of 10.

However, the program actually grants access to the unauthorized user. The reason is that 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 parentheses.

...

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

Compliant Solution

This compliant solution uses an equivalent expression with no The problematic expression could also be written to avoid expressions with side-effects. Rewriting the problematic expression in this manner This allows the expression to be reordered without concern for the evaluation order of the component expressions, making the code easier to understand and maintain.

...