Java: avoid checking for null in nested classes (Deep Null checking)

java 8 null check best practice
java 8 check if object is null or empty
multiple null checks java
optional of null java
java null check best practice
null check in lambda expression java
java stream null pointer exception
java optional

Imagine I have a class Family. It contains a List of Person. Each (class) Person contains a (class) Address. Each (class) Address contains a (class) PostalCode. Any "intermediate" class can be null.

So, is there a simple way to get to PostalCode without having to check for null in every step? i.e., is there a way to avoid the following daisy chaining code? I know there's not "native" Java solution, but was hoping if anyone knows of a library or something. (checked Commons & Guava and didn't see anything)

if(family != null) {
    if(family.getPeople() != null) {
        if(family.people.get(0) != null) {
            if(people.get(0).getAddress() != null) {
                if(people.get(0).getAddress().getPostalCode() != null) {
                    //FINALLY MADE IT TO DO SOMETHING!!!

No, can't change the structure. It's from a service I don't have control over.

No, I can't use Groovy and it's handy "Elvis" operator.

No, I'd prefer not to wait for Java 8 :D

I can't believe I'm the first dev ever to get sick 'n tired of writing code like this, but I haven't been able to find a solution.



-- llappall

Your code behaves the same as

if(family != null &&
  family.getPeople() != null &&
  family.people.get(0) != null && 
  family.people.get(0).getAddress() != null &&
  family.people.get(0).getAddress().getPostalCode() != null) { 
       //My Code

Thanks to short circuiting evaluation, this is also safe, since the second condition will not be evaluated if the first is false, the 3rd won't be evaluated if the 2nd is false,.... and you will not get NPE because if it.

Avoiding Null Checks in Java 8, Well, the obvious answer is to add null checks all around the place. Since null Assuming we have a hierarchical class structure like this: class Outer Resolving a deep nested path in this structure can be kinda awkward. Generally, null variables, references, and collections are tricky to handle in Java code. Not only are they hard to identify, but they're also complex to deal with. As a matter of fact, any miss in dealing with null cannot be identified at compile time and results in a NullPointerException at runtime.

You can use for:


optional equivalent:


Tired of Null Pointer Exceptions? Consider Using Java SE 8's , Java SE 8 introduces a new class called java.util. of a null reference, which will result in a NullPointerException at runtime and stop your program from running further. You don't need to write complex nested conditions to check for null. Since null checks are kinda cumbersome and painful many languages add special syntax for handling null checks via null coalescing operators - also known as elvis operator in languages like Groovy or Kotlin.

The closest you can get is to take advantage of the short-cut rules in conditionals:

if(family != null && family.getPeople() != null && family.people.get(0) != null  && family.people.get(0).getAddress() != null && family.people.get(0).getAddress().getPostalCode() != null) {
                    //FINALLY MADE IT TO DO SOMETHING!!!


By the way, catching an exception instead of testing the condition in advance is a horrible idea.

Null checking in nested getter calls, Let's count the number of times you're writing get . if (people.getImages() != null && people.getImages().size() > 0 && people.getImages().get(0).getUrl() != null)  This was an Introduction to Java 8 Optional. To sum up below are the points you learnt. The NullPointerExceptions in Java occur at runtime and is unexpected. Null checks avoid NullPointerExceptions. However, the code looks ugly. The Optional is an object container provided by Java 8 which encapsulates the object returned by method.

How to avoid null checks in Java?, we can utilize the [code ]Optional[/code] type of Java 8 to prevent null checks. have a hierarchical class structure like this: [code]class Outer { Nested nested;  Java 8 introduced the Optionalclass to make handling of nulls less error-prone. For example, the following program to pick the lucky name has a null check as: For example, the following program to

If, in case, you are using java8 then you may use;

resolve(() -> people.get(0).getAddress().getPostalCode());

public static <T> Optional<T> resolve(Supplier<T> resolver) {
    try {
        T result = resolver.get();
        return Optional.ofNullable(result);
    catch (NullPointerException e) {
        return Optional.empty();

REF: avoid null checks

Avoiding NullPointerException in Java 8, In Java, the null value can be assigned to an object reference, but accessing So, we have to check our variables and objects beforehand. Assuming that we have a nested object with many fields potentially becoming null, we Java 8 introduced many new features among those in an “ Optional ” class. If out is used frequently, the application might be littered with null-checking. Workarounds. I have what I think is a solution but I want to briefly mention a couple of the existing ways of handling it, and why I think we still need something else. Option 1: don’t null check. One school of thought is just don’t null check.

Avoid Check for Null Statement in Java, Learn several strategies for avoiding the all-too-familiar boilerplate In this tutorial, we'll take a look at the need to check for null in Java and various This class also has isNull() and nonNull() methods that can be used as  However, it's worth noting that Optional has become a touchy subject in the Java environment and it's a lot of opinions about where and when to use it. This is however outside the scope of this post. So for further reading, I recommend checking out The Design of Optional by Nicolai Parlog.

Guide To Java 8 Optional, Quick and practical guide to Optional in Java 8. The purpose of the class is to provide a type-level solution for representing optional values instead of null references. To get a deeper understanding of why we should care about the This code checks if the name variable is null or not before going ahead  Java 8 introduced many new features among those in an “Optional” class. This is a value-based class and container object which may or may not contain a non-null value. Let us improve the above

Chapter 10. Using Optional as a better alternative to null, Typically, you can add null checks where necessary (and sometimes, in an excess of In this second attempt, you try to avoid the deeply nested if blocks, adopting a different strategy: When a value is present, the Optional class just wraps it. Java SE 8 introduces a new class called java.util.Optional that can alleviate some of these problems. Let's start with an example to see the dangers of null. Let's consider a nested object structure for a Computer , as illustrated in Figure 1.

  • Sorry, you're stuck. Some people use the trinary conditional operator to make it a little less dense, but it's still the same bytecode, just harder to read.
  • "I can't believe I'm the first dev ever to get sick 'n tired of writing code like this" Well, you're not.
  • Despite all of the answers telling you to ignore null checks and just try to catch a NullPointerException, don't do it! Your code may be an eyesore, but throwing an exception is an expensive operation that you always want to avoid if you can.
  • Also, consider all the good things you can do in "else" clauses if you put them in place - error messaging, alternative code paths, etc. Given all that, it won't look as bad.
  • If only you could port Brototype for Java...
  • It requires API 24 and above :(
  • If you see .map implementation, it uses Objects.requireNonNull(mapper); and this method throws nullpointerexception if the mapper goes null.
  • you've got some accessive } there (forgot to remove them when refactored)
  • This solution relies on catching the NPE which will perform very poorly.
  • I can't think of a situation where it is ok to catch a NullPointerException (maybe there are a few exceptions), it is a bad practice because generally a NPE is a programming error, a correct program should not generate one, when the programmer just catches the NPE it feels like he is trying to cover it up.
  • Reflection isn't exactly cheap either.
  • Yes indeed it can be slow as well @paul . Especially method lookup etc. Actual method invocation though can be quite fast, but again it depends (other optimizations might be harder for the VM). So cacheing the method/field lookups is usually important from my experience if it is needed. Most of all it of course depends on how often the code is used at all.
  • This will never be a suggested approach!!