Skip to content

Add Check Support for Java 21 Record Pattern : New Check PatternVariableAssignment #14949

@mahfouz72

Description

@mahfouz72

child of #14890

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. we should violate mutating variables that are intended to represent matched patterns. So, a new check named PatternVariableAssignment

https://docs.oracle.com/en/java/javase/18/language/pattern-matching-instanceof-operator.html

A pattern is a combination of a predicate, or test, that can be applied to a target and a set of local variables, called pattern variables, that are assigned values extracted from the target only if the test is successful.

Config:

$ cat config.xml 
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
        "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
        "https://checkstyle.org/dtds/configuration_1_3.dtd">

<module name="Checker">
    <module name="TreeWalker">
        <module name="PatternVariableAssignment"/>
    </module>
</module>

Example

public class PatternVariables {
    public void testAssignment(Object obj) {
        if (obj instanceof String s) {
            s = "hello";             // violation
            System.out.println(s);
        }
        if (obj instanceof Rectangle(ColoredPoint x, ColoredPoint y)) {
            x = new ColoredPoint(1, 2, "red");   // violation
        }
        if (obj instanceof Rectangle(ColoredPoint(int x1,int x2,String c), _)) {
            c = "red";   // violation
        }
    }
}

Expected Output

$ java -jar checkstyle-10.19.0-all.jar -c config.xml Test.java 
Starting audit...
[ERROR] D:\Test.java:4:15: Assignment of pattern variable 's' is not allowed.
[ERROR] D:\Test.java:8:15: Assignment of pattern variable 'x' is not allowed.
[ERROR] D:\Test.java:11:15: Assignment of pattern variable 'c' is not allowed.
Audit done.
Checkstyle ends with 3 errors.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions