2

NPEs are described as a "billion dollar mistake". I have to believe a close second may be comparing boxed primitives with "==" instead of .equals(...).

When we have a part of our codebase that returns a Long instead of a long, for example:

class Car {
  Long speed;
}

and

Car carA, carB;
boolean res1 = carA.getSpeed() == carB.getSpeed(); // could fail if the speeds are equal because the wrappers are distinct.

boolean res2 = Objects.equals(carA.getSpeed(), carB.getSpeed()); // compares by value and works

this kind of thing is easy to miss in a PR. Is there a way to generate a warning to catch this situation? We use sonar, FWIW.

IcedDante
  • 6,145
  • 12
  • 57
  • 100
  • I would take a look at git pre-commit hooks. This is not a Java question, but a `git` question. More on a [solution that automatically rejects commits](https://stackoverflow.com/questions/26835998/git-hook-to-reject-commits-where-files-contain-a-specific-string) when a specific string exists. In your case, your PR (not sure what platform you use Github, Gitlab, Bitbucket etc) can display a warning in the PR thread if "==" exists. – azbarcea Sep 22 '21 at 20:20
  • 1
    @azbarcea Rejecting `==` is not workable; this is a context-sensitive question. – chrylis -cautiouslyoptimistic- Sep 22 '21 at 20:57

3 Answers3

3

If you use IntelliJ this will be warned by default

See https://www.jetbrains.com/help/idea/list-of-java-inspections.html#code-maturity for mor details

  • Correct. I can see this being analyzed part of the code static validation (IDE plugin or Coverity or other static analyzers). – azbarcea Sep 22 '21 at 23:29
1

You could also use the spotbugs-maven-plugin which would make the build fail with RC: Suspicious reference comparison (RC_REF_COMPARISON) if it encounters code like this.

  • I somehow lost track of this great feature. It also spotted a few other important bugs in our system. Thanks for the answer! – IcedDante Dec 02 '21 at 14:32
0

I would advice you to use the sonar server (community edition). There specific are rules for equals. There are plugins (SonarLint) to connect your favourite IDEs and also Plugins for the server itself to add other features (like spotbugs etc).

(I am not affiliated with sonarqube but a user of the free sonar server)

Lonzak
  • 9,334
  • 5
  • 57
  • 88