Java Reference
In-Depth Information
}
}
Noncompliant Code Example
In this noncompliant code example, an assignment expression appears as an operand of
the && operator:
Click here to view code image
public void f(boolean a, boolean b, boolean flag) {
while ( (a = b) && flag ) {
/* ... */
}
}
Because && is not a comparison operator, assignment is an illegal operand. Again, this
isfrequentlyacaseoftheprogrammermistakenlyusingtheassignmentoperator = instead
of the equals operator == .
Compliant Solution
When the assignment of b to a is unintentional, this conditional block is now executed
only when a is equal to b and flag is true :
Click here to view code image
public void f(boolean a, boolean b, boolean flag) {
while ( (a == b) && flag ) {
/* ... */
}
}
Applicability
The use of the assignment operator in controlling conditional expressions frequently in-
dicates programmer error and can result in unexpected behavior.
As an exception to this guideline, it is permitted to use the assignment operator in con-
ditional expressions when the assignment is not the controlling expression (that is, the as-
signment is a subexpression), as shown in the following compliant solution.
Search WWH ::




Custom Search