S2259 FP in conditional block that cannot be entered if var is null

S2259 FP appears in both SonarQube Version 8.4.1 (build 35646) and SonarLint for Eclipse 5.9.0.31414. Below in the test method valid is assigned NOT_OK when s == null, so it’s not possible to enter the conditional block if (valid == Valid.OK) {...} when s == null. Thus flagging S2259 for uses of s in that block is a false-positive. This doesn’t happen when using a boolean instead of an enum for valid as in the test2 method.

public class S2259FalsePositive {
  private enum Valid {
    OK, NOT_OK;
  }

  public String test(String s) {
    Valid valid = Valid.OK;
    if (s == null) {
      valid = Valid.NOT_OK;
    }

    if (valid == Valid.OK) {
      return s.toLowerCase(); // FP
    }
    return "";
  }

  public String test2(String s) {
    boolean valid = true;
    if (s == null) {
      valid = false;
    }

    if (valid) {
      return s.toLowerCase(); // No FP
    }
    return "";
  }
}

Sorry for the multiple edits… Rushing too much to translate the actual code to an example. :slight_smile:

Hello @kcondon
thanks for this report. SonarQube 8.4 and SonarLint are both old, non supported, versions. Your SonarQube in particular should have been upgraded months ago and would provide you with many improvements for Java analysis.

This said, I reproduced using the latest version :slight_smile: and will check exactly what happens.
In particular, I’m not certain the Java analyzer is expected to be able to infer that String ‘s’ cannot be null with these indirect conditions.

1 Like

Thanks for checking with the latest version, @Sylvain_Combe. We actually updated to 8.4 quite recently – keeping up with all of the tools and platforms is a challenge. :slight_smile:

It’s interesting that the analyzer is accurate for this rule when the condition is based on a boolean, but not when it’s an enum. Hopefully that will help to refine the analysis.

Regards,
Kevin

1 Like