Why is this an issue?
A common code smell that can hinder the clarity of source code is making assignments within sub-expressions. This practice involves assigning a
value to a variable inside a larger expression, such as within a loop or a conditional statement.
This practice essentially gives a side-effect to a larger expression, thus making it less readable. This often leads to confusion and potential
errors.
Exceptions
This rule ignores assignments in conditions of while
statements and assignments enclosed in relational expressions.
void processInput(BufferedReader br) {
String line;
while ((line = br.readLine()) != null) {
processLine(line);
}
}
Object foo;
if ((foo = bar()) != null) {
// do something with "foo"
}
This rule also ignores chained assignments, including compound assignments.
int j, i = j = 0;
int k = (j += 1);
byte[] result, bresult;
result = (bresult = new byte[len]);
How to fix it
Making assignments within sub-expressions can hinder the clarity of source code.
This practice essentially gives a side-effect to a larger expression, thus making it less readable. This often leads to confusion and potential
errors.
Extracting assignments into separate statements is encouraged to keep the code clear and straightforward.
Code examples
Noncompliant code example
String str;
if (!(str = cont.substring(pos1, pos2)).isEmpty()) { // Noncompliant
// do something with "str"
}
Compliant solution
String str = cont.substring(pos1, pos2);
if (!str.isEmpty()) {
// do something with "str"
}
Resources