java:S5411 false negative on direct method-call form

Product: SonarQube Community (self-hosted)
sonar-java version: sonar-java 8.28.0.43176 on SonarQube Community Build 26.4.0.121862
Java source level: 21 (javac 21, source/target 17)

Rule

java:S5411 — Boxed “Boolean” should not be used in boolean expressions

Description

S5411 inconsistently detects unsafe Boolean unboxing. The rule reports a Boolean used in an if condition only when the value is first assigned to a local variable, but misses the equivalent direct method-call form, even though both can cause the same NullPointerException.

Reproducer

public class Sample {

    public @interface NotNull {}

    @NotNull
    public Boolean get() {
        return Boolean.TRUE;
    }

    // BEFORE — no S5411 reported
    public void runDirect() {
        if (get()) {                // Boolean unboxed in condition
            System.out.println("yes");
        }
    }

    // AFTER — S5411 reported on `if (b)`
    public void runViaLocal() {
        Boolean b = get();
        if (b) {                    // same Boolean, same unboxing
            System.out.println("yes");
        }
    }
}

Hi @Emilyaxe ,

let me clarify about this rule. We don’t raise an issue in case when we can easily define that the expression is annotated @NonNull / @NotNull. So the first negative (marked as // BEFORE — no S5411 reported) is correct, because it calls the method which is marked as @NotNull.

For the second case it’s a little bit more tricky. Here we use almost the same construction, but the problem is that ‘if’ condition uses a variable, and we don’t trace this variable’s assignment, as it can be hard (we can use methods in other classes / libraries). So in such cases the issue will be raised (which is of course FP). You can fix this by assigning javax.annotation.Nonnull annotation to the variable:

@Nonnull Boolean b = get();
if (b) {  // Compliant, 
  System.out.println("yes");
}

Hope it helps. Please let me know if you have any other questions.

Thank you for the explanation.
I will try to assign annotation to the variable!