Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SonarLint Use the primitive boolean expression here

I have the following class Properties:

class Properties {
    private Boolean enabled;

    public Boolean getEnabled() {
        return enabled;
    }
}

If I write the following code, SonarLint gives me a warning on the if condition saying "Use the primitive boolean expression here.".

if (!properties.getEnabled()) {
    return true;
}
// more code

Changing the if condition to the following shuts up the warning. But that less readable, that can't be what SonarLint wants or?

if (properties.getEnabled().equals(Boolean.FALSE)) {
    return true;
}
// more code

What exactly does SonarLint want me to do here? What is the problem?

like image 836
findusl Avatar asked Nov 25 '19 15:11

findusl


2 Answers

As other already mentioned, Sonar wants you to make sure that you don't have any null pointer exception, or at least that's what i have seen too when i do a check before trying to validate against the variable:

if i have the next, Sonar complains

if (properties.getEnabled()) {
       // Your code
}

But if i add a quick validation against nulls, Sonar stops complaining about it

if (properties.getEnabled() != null && properties.getEnabled()) {
       // Your code
}

Now, as you mentioned you can use the Boolean class to use the next

Boolean.TRUE.equals(properties.getEnabled());

As

if (Boolean.TRUE.equals(properties.getEnabled())){
       // Your code
}

It sounds like it's too verbose with Java But internally, they check if the object is of instance Boolean, so they discard the possibility to be null, as explained here: Is null check needed before calling instanceof?

You can check from the git repo what it's accepted and what is not:

https://github.com/SonarSource/sonar-java/blob/master/java-checks/src/test/files/checks/BoxedBooleanExpressionsCheck.java

like image 60
Damonio Avatar answered Sep 22 '22 15:09

Damonio


Use org.apache.commons.lang3.BooleanUtils, it's a null safe way:

if (BooleanUtils.isNotTrue(properties.getEnabled())) {
    return true;
}
like image 31
saffer Avatar answered Sep 19 '22 15:09

saffer