Avoiding null checks in java

November 22, 2023

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.