Core Java

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.

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
EelcoK
EelcoK
9 years ago

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.

Bryan Basham
Bryan Basham
9 years ago

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.

Mike .
Mike .
9 years ago

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”.

Back to top button