Please provide
- Operating system: macOS sonoma
- SonarLint plugin version: 10.12.0.79769
- IntelliJ version: Ultimate 2024.1.6
- Programming language you’re coding in: Java
- Is connected mode used: No
- Connected to SonarCloud or SonarQube (and which version):
And a thorough description of the problem / question:
This is a moderately simplified version of our code where we’re seeing a spurious Bug report about a possible NPE.
static String changeDescription(
BigDecimal triggerValue,
BigDecimal settlementPrice,
Market market
)
{
String changeDescription;
if (settlementPrice != null) {
final var change = triggerValue.subtract(settlementPrice);
changeDescription = descriptionForTradePrice(
market,
change
);
// THE FOLLOWING LINE GENERATES A java:S2259 Bug,
// SAYING THAT '"change" is nullable here'.
// The contract for subtract is to always return a non-null value,
// and `change` is final, so I don't see how an NPE could be thrown.
if (change.compareTo(BigDecimal.ZERO) > 0) {
changeDescription = "+" + changeDescription;
}
} else {
changeDescription = "":
}
return changeDescription;
}
It seems that the linter is somehow diving into the method to which change
is passed and erroneously concluding based on that method that the value can be null so therefore the local call to compareTo
in this method is at risk of an NPE. That analysis seems to be wrong.