Replace .equals() with Objects.equals()

  • A+
Category:Languages

I was writing code, when IntelliJ suggested me a correction on:

objectOne.equals(objectTwo); 

telling me that the Method invocation equals may produce the good old java.lang.NullPointerException , proposing as solution something that I wasn't aware of, Objects.equals:

Objects.equals(objectOne, objectTwo); 

Reading the documentation I see only one potential problem, which is that if objectOne == null and objectTwo == null , then the result is true.

At this point the question is: could I start replacing and using everywhere this method instead of .equals ? Is this a safe approach or I'm missing some big contraindication?

Getting rid of NPE is very attractive... Thanks

 


There is NO bulletproof answer for this question, as it depends on the needs of the program and how it should answer to that exceptional scenario. Saying that, i would say:

If having a null is a programmer error (I mean something that you will never expect to happen inside your algorithms) i would suggest to leave the .equals method as a null pointer exception will arises and make you notice of the problem, i mean, a programmer error (Those error that we don't want!, that means that we wrote bad an algorithm), and you should thanks the application for reporting it (instead of an angry real client....)

But if in the other hand your application could work as well, not considering that as a progrmmer error, then using Object.equals will fit better to your needs.

The general wisdom suggest that exceptions should at leats be logged.

Hope it helps!

TD;DR;

Try to investigate about differnet kinds of exceptions. Not all the exceptions are programmer errors.

In java, usually, the checked exceptions are for all those events that you can anticipate, you can write code that should be able to handle. And the unchecked Exceptions (those that belongs the RuntimeException's family) are for events that you just can not anticipate (like null pointer exceptions), thus it is imposible to write code to handle things that you don't expect (instead you should correct the already existing code, not write new!)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: