Skip to content

UnnecessaryNullCheckWithInstanceOf ignores redundant null check for complex cases. #17137

@Anmol202005

Description

@Anmol202005

I have read check documentation: https://checkstyle.org/checks/coding/unnecessarynullcheckwithinstanceof.html#UnnecessaryNullCheckWithInstanceOf
I have downloaded the latest checkstyle from: https://checkstyle.org/cmdline.html#Download_and_Run
I have executed the cli and showed it below, as cli describes the problem better than 1,000 words

Follow up of : #16489

/var/tmp $ javac Test.java

/var/tmp $ 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>
/var/tmp $ cat Test.java
package com.puppycrawl.tools.checkstyle;

import java.util.Objects;

public class Test {
    public void processData(Object data, String s, String b, String getData) {
        boolean result = false;
        while (getData!= null && getData instanceof String) {
           result = true;
        }
        if (data != null && (!Objects.equals(s, b) || data instanceof String)) {  // false-negative
            boolean isValid = b != null && (s != null || b instanceof String);    //  false-negative
        }

    }
}


/var/tmp $ RUN_LOCALE="-Duser.language=en -Duser.country=US"
/var/tmp $ java $RUN_LOCALE -jar checkstyle-10.24.0-SNAPSHOT-all.jar -c config.xml Test.java
Starting audit...
[ERROR] C:\Users\anmol\IdeaProjects\checkstyle3\src\main\java\com\puppycrawl\tools\checkstyle\Test.java:8:16: Unnecessary nullity check with instanceof operator in conditional expression. [UnnecessaryNullCheckWithInstanceOf]
Audit done.
Checkstyle ends with 1 errors.

the null comparison in redundant in the expression data != null && (!Objects.equals(s, b) || data instanceof String and boolean isValid = b != null && (s != null || b instanceof String therefore a violation is expected at line 11 and 12.


Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions