Why IDEA and Checkstyle think that the expression marked below can be simplified?
public class MySettingDto {
private Boolean enabled;
}
...
public void methodA(MySettingDto setting) {
if (setting == null) {
return;
}
if (setting.getEnable() == true) { <- CAN BE SIMPIFIED
...
}
}
Simplified to if (setting.getEnable())? What about getting NPE when enable flag is null? Maybe it would be better to indicate that if (setting.getEnable()) is in place, it may throw a NPE?
May someone explain me the logic of this kind of message from IDEA?
You can do
if (setting.getEnable()) {…}since you are already working with a Boolean and don’t need to evaluate it.And because you’re not working with a primitive Boolean, you can do
if (Boolean.TRUE.equals(setting.getEnable()) {…}..equals()does a null check internally by usingobj instanceof Booleanwhich prevents NullPointerExceptions.