This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Switching order for equals operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Switching order for equals operator" Watch "Switching order for equals operator" New topic
Author

Switching order for equals operator

Brian Schotky
Greenhorn

Joined: Dec 07, 2009
Posts: 1
Hi all,

I've seen in several places that a way to avoid null pointer exceptions is to switch the order of the equals operator. For example, using



Instead of:



Although this seems like a good idea, doesn't this make it harder to debug down the line if you run into problems? Isn't is basically hiding the fact that you have a NPE where you shouldn't?

Just curious what your thoughts were.

Thanks!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19911
    
  23

In my opinion, you should only write this code if otherwise you would have written In other words, if you already intended to have the null check in place.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 41098
    
  29
If there is any chance of "dog" being null, then dog.equals("Fido") will throw an Exception and "Fido".equals(dog) will not throw an Exception.
Patricia Samuel
Ranch Hand

Joined: Sep 12, 2007
Posts: 300
General Practice is this only that Rob has suggested.

 
I agree. Here's the link: http://kickstarter.com/rocket-mass-heater
 
subject: Switching order for equals operator