File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Switching order for equals operator

 
Brian Schotky
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20381
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47288
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 300
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
General Practice is this only that Rob has suggested.

 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic