Search code examples
javasonarqube

SonarQube Java - Boolean literals should not be redundant - True/Null


I have the followin snippet inside a method:

public void foo(Bar bar){
    this.setSomeField(bar.equals(somePredefinedObject) ? null : true);
}

Sonarqube complains about using the literal true in there. I feel like I can't just get rid of it so easily, because if that expression evaluates to false, I don't pass in false but rather pass in null. For evaluation to true, I pass in true.

Any ideas on how I could go about making sonarqube happy here?


Solution

  • This is SonarQube rule RSPEC-1125

    The solution that they recommend is to change

    booleanVariable = booleanMethod() ? exp : true;
    

    to

    booleanVariable = !booleanMethod() || exp;
    

    Unfortunately, it doesn't work with three-valued logic involving Boolean.TRUE, Boolean.FALSE and null.

    Instead, I think that you should1 write it like this:

    public void foo(Bar bar){
        if (bar.equals(somePredefinedObject) {
           this.setSomeField(null);
        } else {
           this.setSomeField(true);
        }
    }
    

    Or suppress this particular case.

    Arguably, the SonarQube rule is giving a false positive here, though it could also be argued that implementing 3-values logic in this way is a bad idea.


    1 - It is possible that you could trick SonarQube by using a variable containing a reference to Boolean.TRUE, but that is going to make your code harder for other people to read. (Expect comments like "why the heck did you do that??")