IDEA simplified rule that bring to NPE

47 Views Asked by At

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?

1

There are 1 best solutions below

0
TheNytangel On

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 using obj instanceof Boolean which prevents NullPointerExceptions.