PatternVariableAssignment
Since Checkstyle 10.26.0
Description
          Checks for assignment of pattern variables.
        
        
Pattern variable assignment is considered bad programming practice. The pattern variable is meant to be a direct reference to the object being matched. Reassigning it can break this connection and mislead readers.
Examples
To configure the check:
<module name="Checker">
  <module name="TreeWalker">
    <module name="PatternVariableAssignment"/>
  </module>
</module>
Example of violations:
public class Example1 {
  public void testAssignment(Object obj) {
    record Rectangle(Object test1, Object test2) {}
    record ColoredPoint(Object test1, Object test2, Object test3) {}
    if (obj instanceof Integer) {
      Integer z = 5; // ok, 'z' is not a pattern variable
    }
    if (obj instanceof String s) {
      s = "hello"; // violation, "Assignment of pattern variable 's' is not allowed."
      System.out.println(s);
    }
    if (obj instanceof Rectangle(ColoredPoint x, ColoredPoint y)) {
      x = new ColoredPoint(1, 2, "red");
      // violation above, "Assignment of pattern variable 'x' is not allowed."
    }
    if (obj instanceof Rectangle(ColoredPoint(Integer x1,Integer x2,String c),
                                 Integer _)) {
      c = "red"; // violation, "Assignment of pattern variable 'c' is not allowed."
    }
  }
}
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






