In Java, we often see code that compares a particular value to some know constant. Often this is written like this:
someObject.getSomeValue().equals("SomeConstant");
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:
"SomeConstant".equals(someObject.getSomeValue());
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