Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: fixing code for compilation

...

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

Code Block
bgColor#ccccff
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. 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
int number = 17;

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


Exceptions

EXP08-EX1: The postfix increment and postfix decrement operators (++ and --) assign a new value to a variable and then subsequently read it. These are well-understood and are an exception to the rule against reading memory that was written in the same expression.

EXP08-EX2: The logical operators || and && have well-understood short-circuit semantics, so expressions involving these operators may violate this rule. Consider the following code:

Code Block
bgColor#ccccff

public void exampleFunction(){

  InputStream in;
  int i;
  // Skip one char, process next
  while ((i = in.read()) != -1 && (i = in.read()) != -1) {
    // ...
  }

}

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 one assignment and one side effect (the reading of a character from in).

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="003822389c2d8060-f6fc8beb-48c148b6-add69878-8749b88e334fca50998de8ff"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. Bibliography#JLS 05]]

[§15.7, "Evaluation Order"

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.7]

]]></ac:plain-text-body></ac:structured-macro>

 

§15.7.3, "Evaluation Respects Parentheses and Precedence"

...