
...
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
. 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
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 | ||
---|---|---|
| ||
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="e0e81241ba07b87b-8a1646ba-46d04a5f-ae728fa0-5c877608b6db8acb4acf6235"><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> |
|
...