Since Checkstyle 3.0
Checks for assignments in subexpressions, such as in
String s = Integer.toString(i = 2);.
Rationale: Except for the loop idioms, all assignments should occur in their own top-level statement to increase readability. With inner assignments like the one given above, it is difficult to see all places where a variable is set.
Note: Check allows usage of the popular assignments in loops:
String line;
while ((line = bufferedReader.readLine()) != null) { // OK
// process the line
}
for (;(line = bufferedReader.readLine()) != null;) { // OK
// process the line
}
do {
// process the line
}
while ((line = bufferedReader.readLine()) != null); // OK
Assignment inside a condition is not a problem here, as the assignment is surrounded by
an extra pair of parentheses. The comparison is != null and there is no
chance that intention was to write line == reader.readLine().
To configure the check:
<module name="Checker">
<module name="TreeWalker">
<module name="InnerAssignment"/>
</module>
</module>
Example:
public class Example1 {
void foo() throws IOException {
int a, b;
a = b = 5; // violation
a = b += 5; // violation
a = 5;
b = 5;
a = 5; b = 5;
double myDouble;
double[] doubleArray = new double[] {myDouble = 4.5, 15.5}; // violation
String nameOne;
List<String> myList = new ArrayList<String>();
myList.add(nameOne = "tom"); // violation
for (int k = 0; k < 10; k = k + 2) {
// some code
}
boolean someVal;
if (someVal = true) { // violation
// some code
}
while (someVal = false) {} // violation
InputStream is = new FileInputStream("textFile.txt");
while ((b = is.read()) != -1) { // OK, this is a common idiom
// some code
}
}
boolean testMethod() {
boolean val;
return val = true; // violation
}
}
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.coding