If the last object is transferred, should it still be scanned?

Check out the following code:

@Override public int compareTo(final Intersection o) { if (o == null) return 0; double distance = t; double distance2 = ot; if (distance == distance2) return 0; return distance2 > distance ? -1 : 1; } 

Everything seems good, but the fact that 0 can be returned in two different conditional cases bothers me somewhat. If I still move the assignments of the distance and distance2 variables to the beginning, my IDE warns me that

  if (o == null) return 0; 

Then there will be a "dead" code. If this case, in this scenario should not even be checked?


What I mean:

 @Override public int compareTo(final Intersection o) { double distance = t; double distance2 = ot; if (o == null) return 0; if (distance == distance2) return 0; return distance2 > distance ? -1 : 1; } 
+5
source share
4 answers

The final may be zero, it just means that it cannot be assigned and is displayed 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 = ot; // 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; } 
+10
source

Your ideal warns you because the final object may be null and you may get a null pointer exception in

 double distance2 = ot; 

Therefore, the return statement or any statement inside if o == null never reached / will execute

 if (o == null) return 0; 
+2
source

I'm not quite sure why you don't consider this legal or that this cannot happen, because your parameter is final :

 yourClass.compareTo(null); 

You should always check for null in scripts that rely on the instance present, preferably before using the instance.

Marking the final parameter prevents you from actively changing the link or changing the value in the method; this is a way to imagine that this code does not contain any side effects from the passed value.

In addition, I notice a problem with your compareTo method; if the object you are comparing is null , then the comparator designates it as equivalent. You will also encounter extreme cases with NaN and == , since two double values ​​may not be completely equivalent.

You probably need something like this:

 @Override public int compareTo(final Intersection o) { double distance = t; double distance2 = o == null ? 0 : ot; return Double.compare(distance, distance2); } 
+1
source

This is a reference for the object that is being transmitted, and as such it can be null or non-null, regardless of the weather, which is final or not.

+1
source

Source: https://habr.com/ru/post/1209127/


All Articles