Resolve violation of rule S2259: A “NullPointerException” could be thrown; “bar” is nullable here.
What have you tried so far to achieve this
Code is as follows (this is the exact method, I have changed only the symbol names and comparison string value in .contains()).
public boolean isFoo(String bar) {
if (bar != null || bar.isEmpty()) {
return bar.contains("foobar") ;
}
return false;
}
}
Line #2 triggers the following major bug for both conditions in the if statement: A “NullPointerException” could be thrown; “bar” is nullable here.
Yes of course the String is nullable, that is exactly what is being checked for!
Obviously I am not understanding what SQ expects to see here, could someone please enlighten?
Pretend you’re a JVM, executing this code line by line. Assume for this test case that bar is null. Walk through each line and condition. If bar is null, then “bar != null” will be false. If that’s the case, then it will attempt to evaluate the next condition, being “bar.isEmpty()”, which will then throw a NullPointerException.
The line likely should have been:
if (bar != null && bar.isNotEmpty()) {
If you have the commons-lang library in scope, then this might be even better:
I thought JVM would shortcut on AND conditions?
i.e. if the first one is false because bar is indeed null, then it automatically “knows” that it does not need to bother evaluating the second condition?
Sure, the JVM will do “short-circuiting” for logical operations. It will do that for ANDs and ORs, but you don’t have an AND, you have an OR. The algorithm is different for ANDs and ORs.