InnerAssignment
Since Checkstyle 3.0
Description
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()
.
Examples
To configure the check:
<module name="Checker">
<module name="TreeWalker">
<module name="InnerAssignment"/>
</module>
</module>
Example 1:
public class Example1 {
void foo() throws IOException {
int a, b;
a = b = 5; // violation, 'Inner assignments should be avoided'
a = b += 5; // violation, 'Inner assignments should be avoided'
a = 5;
b = 5;
a = 5; b = 5;
double myDouble;
double[] doubleArray = new double[] {myDouble = 4.5, 15.5};
// violation above, 'Inner assignments should be avoided'
String nameOne;
List<String> myList = new ArrayList<String>();
myList.add(nameOne = "tom"); // violation, 'Inner assignments should be avoided'
for (int k = 0; k < 10; k = k + 2) {
// some code
}
boolean someVal;
if (someVal = true) { // violation, 'Inner assignments should be avoided'
// some code
}
while (someVal = false) {} // violation, 'Inner assignments should be avoided'
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, 'Inner assignments should be avoided'
}
}
Example 2:
public class Example2 {
public void test1(int mode) {
int x = 0;
x = switch (mode) {
case 1 -> x = 1; // violation, 'Inner assignments should be avoided'
case 2 -> {
yield x = 2; // violation, 'Inner assignments should be avoided'
}
default -> x = 0; // violation, 'Inner assignments should be avoided'
};
}
public void test2(int mode) {
int x = 0;
switch(mode) {
case 2 -> {
x = 2;
}
case 1 -> x = 1;
}
}
public void test3(int mode) {
int x = 0, y = 0;
switch(mode) {
case 1:
case 2: {
x = y = 2; // violation, 'Inner assignments should be avoided'
}
case 4:
case 5:
x = 1;
}
}
}
Example of Usage
Violation Messages
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Package
com.puppycrawl.tools.checkstyle.checks.coding