False positive on java:S2259

Must-share information (formatted with Markdown):

  • which versions are you using: SonarQube Enterprise Edition v10.6 (92116)
  • how is SonarQube deployed: Docker

Hello Sonar team

Looks like we have a false positive with java:S2259 A “NullPointerException” could be thrown; “block()” can return null.

        if (applicationServers == null || applicationServers.block() == null) {
            return "Failed to get application servers for deployment description %s".formatted(deploymentDescription);
        }
        this.url = applicationServers.block().getUrl();

the issue is raised on line
this.url = applicationServers.block().getUrl();
despite the fact we check for nullability just before

With :heart:
Xavier

Hi @Xav,

Thank you for the report.

Unfortunately, it is not as trivial for a static code analysis tool to make the same assumption in this case. It is, in general, not feasible to reliably determine whether a method like block() returns a non-null value just because it has returned a non-null value before.

To give an illustrative example, block() might be implemented to return null on every second call, or even randomly. Now, I don’t know your implementation of block(), and in some cases, it may be possible to conclude that a method returns the same value when called multiple times. However, the general case is the problem.

Instead, I suggest assigning the return value of the call to block() to a variable and using that subsequently. This guarantees that the value will not change between the conditional expression and the then-branch.