Reputation: 269
Please advise what are the best way to avoid to avoid NullPointerException by applying careful or defensive coding technique and null safe API methods. spceially while coding in java , one thing that I have analysed is to put null check and is there any custom template also you can advise for eclipse editor which we can use..!!
Upvotes: 0
Views: 222
Reputation: 272337
One useful pattern is the Option pattern. It's used widely in Scala, and a Java equivalent is discussed here.
Briefly, instead of returning a reference to an object, you return an Option object. One subclass (Some) contains the reference, and the another subclass (None) doesn't. Thus the API explicitly states that you may not get a value back. You have to determine what you've been given in order to get back the underlying reference.
e.g. (pseudocode)
Option<String> value = findNameForId(34);
if (value instanceof Some) {
return ((Some<String>)value).get();
}
else {
throw new Exception();
}
It's rather verbose in Java, but considerably less so in Scala.
findNameForId(34) match {
case Some(id) => id
case None => throw new Exception
}
You can make it even more concise in Scala, viz:
findNameForId(34).getOrElse(throw new Exception)
or
findNameForId(34).getOrElse(DefaultValue)
Upvotes: 0
Reputation: 8582
Well, if you call a function and null is a possible return value, then you have to check for it. On the other hand, if you check for null everywhere, it would be too defensive and make the code confusing. If you have access to source codes and/or javadoc, you can check if the function will return null or won't.
Sometimes if you expect a value but the variable is null, you have to throw an exception, so NPE can be useful in that case, because there is an error elsewhere.
Also, there are some annotations like @NonNull or @Nullable that some static analysis checkers (like Findbugs) use to help them catch possible null pointer issues.
For the functions you are building, check if it makes sense to return null. For instance, if your function returns a collection, there is a difference between returning an empty collection and returning null.
More reading: Null Object Pattern
Upvotes: 4
Reputation: 23443
Check for null dereferences before operating on the object.
if(something != null) // do dome thing.
Use yoda notation if you wish to dismiss null dereferences.
if("yes".equals(something) // do something
Eclipse editor plugin? Maybe you can use style check.
Upvotes: 1