Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If final object is being passed, should null still be checked?

Tags:

java

Check out the following code:

    @Override
    public int compareTo(final Intersection o) {
        if (o == null) 
            return 0;

        double distance = t;
        double distance2 = o.t;

        if (distance == distance2) 
            return 0;


        return distance2 > distance ? -1 : 1;
    }

All seems well however the fact that 0 may be returned on two different conditional occasions does somewhat bother me. If I do however move the variable assignments of distance and distance2 to the top, my IDE warns me that

            if (o == null) 
              return 0;

Would then be 'dead' code. If that's the case, should null even be checked in this scenario?


What I mean is:

@Override
    public int compareTo(final Intersection o) {

        double distance = t;
        double distance2 = o.t;

        if (o == null) 
            return 0;

        if (distance == distance2) 
            return 0;


        return distance2 > distance ? -1 : 1;
    }
like image 525
Juxhin Avatar asked Dec 15 '14 16:12

Juxhin


2 Answers

Final may be null, it just means it cannot be assigned and is visible in anonymous inner classes etc.

In your case, the problem is different: (see comments)

public int compareTo(final Intersection o) {

    double distance = t;
    double distance2 = o.t; // here you use it, potentially causing NPE

    if (o == null) // if o was null, this is never reached
        return 0;

    if (distance == distance2) 
        return 0;


    return distance2 > distance ? -1 : 1;
}
like image 123
MightyPork Avatar answered Sep 20 '22 11:09

MightyPork


Your ide warns you because a final object can be null and you can get a null pointer exception on

double distance2 = o.t;

Hence the return statement or any statement inside the if o == null will never reach/execute

if (o == null) 
   return 0;
like image 29
sol4me Avatar answered Sep 22 '22 11:09

sol4me