There is a form of driving called "defensive driving". Defensive drivers anticipate accidents and bad drivers. This lowers the chances of getting into accidents. It has saved me from several bad accidents.
Similarly, we can avoid the scary NullPointerException
in Java if we know how to anticipate it.
For example, what is wrong with this if
check?
if (aString.equals("yes")) { /* do stuff */ }
It's assuming that aString
has been initialized. If a string is not initialized, it will be null
! Calling .equals()
on a null
object is not going to end well. This happens more often than you might expect. It is better to write this:
if ("yes".equals(aString)) { /* do stuff */ }
I edited a POJO recently that was meant to represent a deserialized JSON object. The business requirements said I needed to remove any leading or trailing whitespace. Thankfully, the String.trim()
method can do this for me in a single line! I placed it in the setter like this:
public class Person {
private String firstName;
public String getFirstName() { return this.firstName; }
public void setFirstName(String firstName) {
this.firstName = firstName.trim();
}
}
Seems innocent enough. 😉
Imagine my frustration when converting a JSON to this object was throwing a com.fasterxml.jackson.databind.JsonMappingException
with a not-so-helpful explanation of "N/A". What was happening???
Apparently, if firstName
is null
in JSON, setFirstName(firstName)
was calling trim()
on a null
object!
What I need to do is check to make sure that the String parameter in setFirstName(firstName)
is not null. There's more than one way to check, but I chose a ternary operator:
public class Person {
private String firstName;
public String getFirstName() { return this.firstName; }
public void setFirstName(String firstName) {
this.firstName = (firstName == null) ? null : firstName.trim();
}
}
How about you? Have you run into the dreaded NullPointerException
recently? How did you fix it?
Top comments (6)
Oh yeah... the bad old
NullPointerException
. It's called "The Billion Dollar Mistake" for a reason. ;-)I try to fight this devil wherever I can. For me, the most important rules are
I'm so annoyed by this subject, that I'm writing a little rant post about it myself at the moment. :-D
The post will focus on the "Null Object Pattern" as one of the solutions. I hope I will get it done soon.
Nice article. Keep up the good work.
Thanks, Lars! Yeah, it can be a real pain in the behind!!!
I've come to realize that there's only one way to truly eliminate NullPointerExceptions on the JVM.
Use Kotlin.
It's 2019, the Null-Problem has been solved, and solved well.
Looking into Kotlin because I've heard so many good things about it.
Option 1)use @Nullable, @NonNull
Option 2) use Kotlin 💚
I'm looking into Kotlin, for sure!