Part 2: Avoiding Null-Pointer Exceptions in a Modern Java Application

Jens Christian B. Madsen
Destination AARhus-TechBlog
10 min readAug 21, 2020

There’s got to be a better way — modern null handling

In the previous post - part 1, we saw how in some cases null is a necessary evil and that there are right and wrong ways to use it. In this post, I will cover how you can best work safely with null values and discuss some of the solutions, we use in the Columna project to avoid errors and elegantly handle null.

Return Optional over null

While I hopefully convinced you in the previous post that returning null is correct in some cases. In this post, I am going to tell you that you shouldn’t if you can avoid it. Whenever you add a new method to the code base that may return nothing, you should strive to use the Optional type instead of null. The Optional type was introduced in Java 8 and is a generic container for any object. It was introduced to give developers a way to indicate that a method might return nothing, which you previously couldn’t (at least not without annotations — more on that below). There are two types of Optional objects: Those that hold a value and those that don’t. The former is created with the value to hold, whereas the latter is simply a static singleton. The typical use case has the following structure:

if (checkSomeCondition(someValue)){
return Optional.of(someValue);
} else {
return Optional.empty();

To see why an Optional-based method signature is superior, assume a method with the following signature:

public Admission getAdmission(Patient patient)

The signature only tells you that it returns an object of type Admission. As discussed above, null corresponds to every type. Unless we analyze the implementation of the method, we have no way to know if null is returned. In contrast, a method returning an Optional looks like this.

public Optional<Admission> getAdmission(Patient patient)

Since it only makes sense to return an Optional, where an empty value must be returned, the method must return an empty value. Whenever you get an Optional from a method, you know that there’s a possibility of receiving nothing and must handle the value appropriately.