Skip to content
Advertisement

Replace .equals() with Objects.equals()

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

Advertisement

Answer

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’s 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 arise and make you take notice of the problem, I mean, a programmer’s error (Those errors 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 programmer error, then using Object.equals will fit better to your needs.

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

Summary

Try to investigate about different 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 impossible to write code to handle things that you don’t expect (instead you should correct the already existing code, not writing new code!).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement