Null Pointer Exception is the most common and most annoying exception in Java.
In this post I want to avoid this undesired exception.
First let's create example that raise Null Pointer Exception
private Boolean isFinished(String status) {
if (status.equalsIgnoreCase("Finish")) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
}
In previous method if we pass the value of "status" variable as null it will raise Null Pointer Exception in below line
if (status.equalsIgnoreCase("Finish")) {
So we should change my code to below code to avoid Null Pointer Exception
private Boolean isFinished(String status) {
if ("Finish".equalsIgnoreCase(status)) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
}
In previous method if we path the value of "status" variable as null it will not raise Null Pointer Exception.
Conclusion
If you have object.equals(”literal”) you should replace with “literal”.equals(object) .
If you have object.equals(Enum.enumElement) you should replace with Enum.enumElement.equals(object).
At general expose equals method of the object that you are sure that it doesn't has null value.
Thanks
Good suggestion.One of my colleagues suggested this trick to me and I have been able to avoid the null pointers occurring due to object.equals("String") especially when the value of object is not in your control.
ReplyDeleteAvoiding NPEs is good, but if null is not a valid input for this function, the solution presented is just hiding another error. You could add an assert for testing and/or throw an IllegalArgumentException for unexpected input.
ReplyDeleteMy personal tip for avoiding NPEs is to never intentionally return null from a function. I.e. don't use null as a synonym for "no result" or "false."
Avoiding NPE doesn't mean that return null of function but I present best practice of how prevent your code not throw NPE and I am agree with you to Asset and/or throw exception because of null value
DeleteI think that this masking the null object. I completely agree with the above comment. I do this on a regular basis:
ReplyDeleteFor example:
Assert.notNull(status);
I am also agree with you to assert but what I present is to avoid my code itself to throw NPE
DeleteBut if business utself throw NPE I should assert and/or throw exception
It is a well known "trick" to avoid NPE. In this case a null value for status is allowed and the method simply would return false. I think the tilte of the post should be "avoiding null check", since another implementation could be
Deleteif (status == null) return false;
return status.equalsIgnoreCase("Finish");
For the sake of shortness I would prefer the one liner implementation:
return "Finish".equalsIgnoreCase(status);
but that's another topic
This comment has been removed by the author.
Deleteagreed with the two ano's above. In addition, if you do it don't code it yourself but use StringUtils from apache commons-lang3.
ReplyDeleteorg.apache.commons.StringUtils.equals(..,..);
Funny, I just today suggested that we switch back from our recommendation of using CONSTANT.equals(value) to value.equals(CONSTANT) as others mentioned as well null is a "bad citizen" in Java. Like one of my former colleagues put it:
ReplyDelete"null may be used for everything and is useful for nothing" :-)
We use StringUtils.equals for all string comparisons in order to avoid null pointer exceptions.
ReplyDeleteWe return an instance of Optional (http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Optional.html) from methods where nothing could be returned e.g. find(final long id) in a DAO.
Ok I will write about org.apache.commons.lang.StringUtils class in the next post (second part)
DeleteI posted Part2 related to this post also
ReplyDeletehttp://mahmoudoracle.blogspot.com/2012/05/acoid-null-pointer-exception-part-2.html