We are checking the quality of our code using Sonar, and Sonar found code which compares objects for identity like this:
if (cellOfInterest == currentCell) { … }
Sonar finds this kind of identity check peculiar enough to call it critical and proposes to replace the identity check (using ==
) with a check for equality (using .equals()
instead). Identity checks, so the rationale behind this, are often not what is meant.
In our case, however, we iterate through a list of Cell
s and check in each iteration (currentCell
) whether we are handling a special cell we already have (cellOfInterest
).
I'd like to hear if there are other patterns than ours which are common and which avoid this issue simply by using a different design. Or what solutions do you propose to avoid using an identity check in the mentioned situation?
We considered a replacement of the identity check with an equality check as described above but it does not seem applicable in our situation because other cells might be "equal" as well but not identical.
All ideas are welcome!
For Strings and most other Java objects, it is possible to have 2 instances which are identity unequal but are actually equivalent by
.equals
. It's conventional to avoid==
for comparison (using equals or compareTo instead) but if it works, it works. You can mark the item as a false positive in SonarQube.