Tuesday, November 20, 2007

A quick and easy way to minimize java.lang.NullPointerExceptions

In Java, we often see code that compares a particular value to some know constant. Often this is written like this:


This works ok, assuming that someObject is not null, and as long as you are sure that getSomeValue() will never be null.

If you aren't so sure, or if you just want to develop a good habits that will minimize the number of NullPointerExceptions you run into, you may try to write the same comparison this way:


You are ensuring that you will not run into the dreaded java.lang.NullPointerException, because your constant value will never be null. And you are improving your own productivity, because you and your teammates will spend less time tracking down and fixing NullPointerExceptions.

No comments:

Post a Comment