FP on java:S5411 (Boxed "Boolean" should be avoided in boolean expressions)

  • versions used (SonarQube, Scanner, Plugin, and any relevant extension)
    SonarQube Version: 8.2.0.32929
  • error observed (wrap logs/code around triple quote ``` for proper formatting)
    False positive, believes method returning a boolean annotated NotNull be null and throw a NullPointerException.
  • steps to reproduce
public class Test {
    public static void main(String[] args) {
        if(getBoolean()) {
            System.out.println("Test");
        }
    }
    
    @NotNull
    public Boolean getBoolean() {
        return true;
    }
}
  • potential workaround
    Respect Nullable and NotNull annotations

Hi,

I agree that it’s a false-positive to state that a method returning a @NotNull Boolean could be null.
But before improving the rule S5411 to support this case, I would be interested to know why a developer would chose to return a @NotNull Boolean instead of a boolean. Could you share some context where it makes sense?

If any generics are used, then it casts to Boolean instead of boolean, that’s usually what causes the FP.

example:

public class GenericClass<T> {
    private T value;
    public GenericClass(@NotNull T value) {
        this.value = value;
    }

    @NotNull
    public T getValue() {
        return value;
    }
}

public class Main {
    public static void main(String[] args) {
        GenericClass generic = new GenericClass(true);
        //False positive
        if(generic.getValue()) {
            ...
        }
    }
}

Obviously the class is a useless wrapper in this case but you get the idea.

Ticket created SONARJAVA-3370. Thanks for your feedback.