8000 Add Check Support for Java 21 Record Pattern : New Check UnnecessaryNullCheckWithInstanceof · Issue #14945 · checkstyle/checkstyle · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Add Check Support for Java 21 Record Pattern : New Check UnnecessaryNullCheckWithInstanceof #14945
Closed
@mahfouz72

Description

@mahfouz72

child of #14890
Previously proposed in #6943

when using pattern matching with instance of, the null-check is redundant as instanceof operator implies non-nullity. It will be good if we have a check that violates this redundant condition to lead to a more concise and clear code

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="UnnecessaryNullCheckWithInstanceof"/>
    </module>
</module>

Example 1

public class Test {
   void test(Object obj) {
        if (obj != null && obj instanceof String) {   // violation
            System.out.println("string");
        }
    }
}

Expected Output

$ java -jar checkstyle-10.19.0-all.jar -c config.xml Test.java 
Starting audit...
[ERROR] D:\Test.java:3:17: Unnecessary nullity check with instanceof operator in conditional expression.
Audit done.
Checkstyle ends with 1 errors.

the check should violate the null check here because Condition obj != null is covered by subsequent
condition obj instanceof String `


Example 2

class Test {
    record ColoredPoint(int x, int y, String c) { }
    void test(Object obj) {
        if (obj instanceof ColoredPoint(_,_,_) && obj != null) { // violation
            System.out.println("string");
        }
    }
}

Expected Output

$ java -jar checkstyle-10.19.0-all.jar -c config.xml Test.java 
Starting audit...
[ERROR] D:\Test.java:4:55: Unnecessary nullity check with instanceof operator in conditional expression.
Audit done.
Checkstyle ends with 1 errors.

the check should violate the null check here because Condition obj != null is always 'true' when reached

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    0