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?
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
Use org.apache.commons.lang3.BooleanUtils, it's a null safe way:
if (BooleanUtils.isNotTrue(properties.getEnabled())) {
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With