Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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??")

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading