False positive for java:S2259 when using ternary operators

  • versions used Sonarqube 8.5.1, SonarJAVA

In case of a ternary operator the rule is resulting in a false positive.

The following code triggers a S2259 while body cannot be null when calling getTradegroup.

return response != null && response.getBody() != null ? response.getBody().getTradegroup() : new ArrayList<>();

Kind Regards,
Devon Britton.

Hello @DevonBritton,

To me, this is not a false positive: you can not assume that two consecutive calls to getBody() return the same value, if the second returns null , you will have a NPE. Extracting this call into a variable would make the code safer and cleaner, as it will also potentially prevent duplicated computation.

Does it make sense to you?

Hi @Quentin

That makes sense. The field “body” is final, so once assigned it can’t be reassigned afterwards, so 2 consecutive calls to getBody() should not suddenly change the result. But you can’t assume that either, as the state of body can always have been adapted which could result the logic inside getBody() to return null.
All that in matter of nanoseconds…but in theory it’s possible.

The above is contextual though, Sonar can’t assume all of the above so you’re right, not a false positive from a rule perspective.

Thanks for the assistance.

Kind Regards,
Devon Britton.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.