...
In this noncompliant code example, an assignment expression is the outermost expression in an if
statement.
Code Block | ||
---|---|---|
| ||
public void exampleFunction(Object a, Object b){ if (a = b) { /* ... */ } } |
While the intent of the code could be to assign b
to a
and test the value of the result for equality to zero, it is frequently a case of the programmer mistakenly using the assignment operator =
instead of the equals operator ==
.
...
When the assignment of b
to a
is unintended, this conditional block is now executed when a
is equal to b
.
Code Block | ||
---|---|---|
| ||
public void exampleFunction(Object a, Object b){ if (a == b) { /* ... */ } } |
When the assignment is intended, the following compliant solution may be used because the programmer's intent is clearer:
Code Block | ||
---|---|---|
| ||
public void exampleFunction(Object a, Object b){ if ((a = b) == true) { /* ... */ } } |
Although it could be preferable to express this same logic as an assignment followed by a conditional:
Code Block | ||
---|---|---|
| ||
public void exampleFunction(Object a, Object b){ a = b; if (a == 0) { /* ... */ } } |
Risk Assessment
Errors of omission can result in unintended program flow.
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4f9481325a8a0432-9f59576a-48354477-b86196c7-08b7b7abdf06468394d7436a"><ac:plain-text-body><![CDATA[ | [[Hatton 1995 | AA. Bibliography#Hatton 95]] | Section 2.7.2, "Errors of omission and addition" | ]]></ac:plain-text-body></ac:structured-macro> |
...