About Patroklos Papapetrou

Patroklos is an experienced JavaEE Software Engineer and an Agile enthusiast seeking excellence in software quality. He is also co-Author of the Sonar in Action book, and contributor of several Sonar plugins.

Avoiding Null Checks In Java

One of the worst nightmares for java developers ( from junior to experts ) is null object reference checking. I’m pretty sure you have seen several times code like this:
 
 
 
 
 
 
 
 
 

public void addAddressToCustomer(Customer customer, Address newAddress){
 if ( cutomer == null || newAddress == null)
 return;
 
 if ( customer.getAddresses() == null ){
   customer.setAddresses ( new ArrayList<>());
 }
 customer.addAddress(newAddress);
}

Personally I hate writing code for null check. In this post I will list some of the things that have worked well for me and are based on my personal experience in production environments and systems.

  • Stop checking for null objects in all layers. Limit the checks only on the upper layers such as UI layer, presentation layer or the layer of your API controllers. In other words ensure that no null objects are passed from upper layers to the business logic layer.  For instance if you are developing a standard web application using Spring annotations then you’re probably have some classes annotated with @Repository , @Service , @Controller. Controllers are responsible for receiving client’s data and pass it to the @Service class for processing. It’s their responsibility to ensure that NO null objects are passed to the service layer. Service classes and below should not be null-safe. If they’re invoked with nulls then they should throw NPE to warn developers that they should fix this error. Remember that NPE is not a user error but a developer’s error and it should be always avoided.  Do the same with user inputs that comes from html forms or other user interface input.
  • If you follow the above approach you won’t be tempted anymore to write business logic based on the fact that an object is null or not. Null objects should not be used to decide the behavior of your system. They are exceptional values and should be treated like errors and not valid business logic state.
  • When returning a list from a method, always return an empty list instead of null. This will allow clients to iterate the list without checking for nulls. Iterating an empty list is totally accepted and will just do nothing, whereas iterating a null list will throw a NPE.
  • In your persistent layer when you search for a specific object (i.e. using its identifier) and it’s not found then a very common approach is to return a null object. Well, this will make all clients to manually check for this null case. In this case you have two alternatives. Either throw a run-time exception (i.e. ObjectNotFoundException ) or return an empty Object. I have used both of these options and my suggestion is to evaluate them depending on the overall architecture of your system and the tools / frameworks used.
  • When comparing a strings always put first the string that is less possible to be null so instead of:
customer.getAddress().getStreet().equals("Times Square")

prefer:

"Times Square".equals(customer.getAddress().getStreet())
  • If you’re using or planning to use Java8 then the new Optional class is here for you. Check this article that clearly explains the use of Optional.

Next time you’re going to write some null check code try to think a little and decide if it’s redundant or not.

Reference: Avoiding Null Checks In Java from our JCG partner Patroklos Papapetrou at the Only Software matters blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

3 Responses to "Avoiding Null Checks In Java"

  1. EelcoK says:

    Nice article. We use JSR 305 package annotations, making it part of our software validity checks. This makes all parameters non-null by default unless you specifically annotate it to be nullable. Makes it easier to prevent NullPointerExceptions and similar problems.

  2. Bryan Basham says:

    I would also recommend using Optional (either the Guava version for pre-Java8 or java.util.Optional in Java8) to represent APIs where you might have “zero or one” of something.

  3. Mike . says:

    I agree with NPE are bugs. That’s why I regularly use assert to check for NULL.
    It’s one line of code hence doesn’t clutter my code too much and
    active only during development via -ea thus won’t impact performance on “life”.

Leave a Reply


− three = 4



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close