java:S2259 to prevent false result using Bitwise exclusive Or "^" for first if boolean parm

Think found a bug where the Sonar Analysis wrongly reports possible null pointer exception when the first if boolean param has been set by Bitwise exclusive Or “^”.

Rule

A “NullPointerException” could be thrown; “oldProspectFieldSetting” is nullable here.
Get permalink
Null pointers should not be dereferenced. java:S2259

Workaround

// SonarQube workaround, using 'Logical or' Operator instead of 'Bitwise exclusive OR' to avoid wrongly reported potential null pointer error
final boolean toOrFromNull = Objects.isNull(newProspectFieldSetting) || Objects.isNull(oldProspectFieldSetting);
if (toOrFromNull || !objectOne.getName().equals(objectTwo.getName())) {
  // bla bla
}

SonarQube Bug (Reporting)

final boolean toOrFromNull = Objects.isNull(objectOne) ^ Objects.isNull(objectTwo);
if (toOrFromNull || !objectOne.getName().equals(objectTwo.getName())) {
 // bla bla
}

Hi @DSEyers,
I don’t see any S2259 false-positive in the SonarQube Bug (Reporting) code above.

toOrFromNull is false in two different cases:

  • objectOne == null && objectTwo == null
  • objectOne != null && objectTwo != null

So in the case objectOne == null && objectTwo == null then toOrFromNull is false.
If toOrFromNullis false, the program will evaluate the rest of the condition after ||:

  • !objectOne.getName().equals(objectTwo.getName())

And throw a NPE on objectTwo.getName()

WDYT?

1 Like