blackpanther
blackpanther

Reputation: 11486

Not-nullity requirement or principle

I have just read in Effective Java that the fifth principle of the equals() method is that all objects must be unequal to null. The book goes on to say that some classes written by programmers guard against this using an explicit test for null:

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

According to Effective Java, the above not null test is unnecessary. However, my question is, why then do so many programmers test for this not-nullity requirement?

Upvotes: 7

Views: 424

Answers (5)

Navs
Navs

Reputation: 185

To prevent a NullPointerException when equals() is called.

Upvotes: 0

Harish Kumar
Harish Kumar

Reputation: 528

There are many practices suggested in industry so to avoid unnecessary checks or pitfalls in code but the fact that mistakes can happen or there can be situations that one cannot control like data coming from some third party system having values missing which one's system is expecting so the checks are required. The world is not perfect !!

Upvotes: 0

rs'
rs'

Reputation: 311

possible reasons to check:

old habits from other languages

not being familiar with the principle you mentioned

libraries which may throw null pointer exceptions ( you can't guarantee that someone else hasn't done something stupid! )

if you have a few nested commands that only need to be evaluated for a non null instance of your object you might want to bypass

Upvotes: 0

Joonas Pulakka
Joonas Pulakka

Reputation: 36577

You can do that with an instanceof test:

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

null is not instance of anything, so this works.

Upvotes: 8

stinepike
stinepike

Reputation: 54692

Object firstObject = null;
secondObject.equals(firstObject);

how can you prevent this?? if you dont' check null before using it then it will crash. I think you will also need to check the class type like following

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

Upvotes: 2

Related Questions