I’m currently working with the rule java:S2259 for detecting potential NullPointerExceptions (NPEs) in Java code. However, I’ve noticed some inconsistencies in its behavior. Specifically:
In the following examples, the rule fails to detect an NPE:
public class NpeCheckerTestFile {
public Integer process(List<Integer> a) {
if(CollectionUtils.isEmpty(a)){
int x = a.get(0) + a.get(1); // Noncompliant
}
return 0;// compliant : unreachable.
}
}
// 2nd File, synonymous to My personal-Util Functions in my repo.
public class NPECheckerTestFile2 {
public static boolean isEmpCollection(List<?> collection) {
return collection == null || collection.isEmpty();
}
}
Observation
When the code is split across multiple classes or files, the rule does not flag the NPE as expected.
However, if the utility functions (like isEmpCollection) or both classes are in the same file, the NPE is detected correctly.
This discrepancy makes it challenging to rely on java:S2259, since projects often use utility functions and class separation.
Is there a known workaround or configuration for SonarQube or this specific rule to ensure accurate detection in such cases? If not, are there any plans to enhance java:S2259 to account for cross-class and cross-file NPE scenarios?
in order to be sure I would need to see what the CollectionUtils.isEmpty method does, but assuming that it only checks the .size() == 0 of a collection, I would say that the exception that could be raised is something like IndexOutOfBoundsException and not an NPE.
Can you clarify why you would expect a NullPointerException?
Also no, there are no plans to improve this rule, as it will be replaced in the future by a different one.
Hey there, you have correctly identified where the engine is pulling his knowledge from, we try to track the most popular library methods with this behavior cache.
This particular method was tracked this way to avoid potential FPs. If you mark the collection as nullable on the true path of the utility method, it will propagate further, possibly creating noise and FPs. When you enter the true path of that method, it means that the collection is either null, or not null but empty, so the engine avoids marking it as nullable