InnerAssignment

Since Checkstyle 3.0

Description

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().

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
    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
  }
}
        

Example 2:

public class Example2 {
  public void test1(int mode) {
    int x = 0;
    x = switch (mode) {
      case 1 -> x = 1;  // violation
      case 2 -> {
        yield x = 2; // violation
      }
      default -> x = 0; // violation
    };
  }
  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
      }
      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

Parent Module

TreeWalker