Claim or principle of invalidity

I just read in Effective Java that the fifth principle of the equals() method is that all objects must be unequal with null . The book further states that some classes written by programmers protect this using an explicit test for null :

 public boolean equals(Object o){ if (o == null) return false; ... } 

According to efficient Java, the above non-zero test is not needed. However, my question is, why then do many programmers test this non-nullity requirement?

+7
source share
5 answers

You can do this with the instanceof test:

 public boolean equals(Object o){ if (!(o instanceof MyObject)) return false; ... } 

null not an instance of anything, so this works.

+8
source
 Object firstObject = null; secondObject.equals(firstObject); 

how can you prevent this? if you do not check the null value before using it, it will crash. I think you will also need to check the type of the class as shown below.

  if (other == null || other.getClass() != this.getClass()) { return false; } 
+2
source

To prevent a NullPointerException when equals() called.

0
source

Possible reasons for checking:

old habits from other languages

not familiar with the principle you indicated

libraries that can throw null pointer exceptions (you cannot guarantee that someone else has not done something stupid!)

if you have several nested commands that should only be evaluated for a null instance of your object, you can work around

0
source

There are many practices in the industry to avoid unnecessary checks or errors in the code, but the fact that errors may occur or there may be situations that cannot be controlled, for example, data coming from any third system, having values ​​that are absent, waiting that checks will be required. The world is not perfect!

0
source

All Articles