Java null Handling Best Practices


null is nor an Object neither a type. It’s just a particular value, which can be assigned to any reference type.

null references can only be used in a boolean test, to check if an object is null. any other use will throw a NullPointerException

NullPointerException is the most common exception. avoiding null references make your application code cleaner and easier to understand

When a method is returning a null value, it’s a risky situation since there is no way to ensure that the caller always does a check-for-null.

We will also see some cases where it is advisable to assign null … to avoid storage leaks. 

Initialize variable with null in java

Initializeing fields is key in a programming language. Any reference variable in Java has default value null.

According to  Java Language Specification :

Each class variable, instance variable, or array component is initialized with a default value when it is created…

For all reference types, the default value is null.

Therefore, setting fields to null is unnecessary and useless code.

 

Empty object vs null java

You probably already know that one of the most common problems encountered during development: the NullPointerException.

To avoid this, there are many cases where a developer should use empty objects rather than a null object reference

What do we mean by an empty object?

  • The empty String  

                  String item = “”;

  • Arrays, collections…with 0 items

                 BigDecimal[] items = new BigDecimal[0];

                 List<Integer> items = new ArrayList<>();

 

Using an empty object instead of a null reference simplifies the code since we don’t need to check each time if the object is null.

 

Return empty collection best practices

In addition, for Collections it’s preferable to use the type-safe methods that return empty items. 

The benefit is, emptyList() might not create a new object with each call.

Implementations of this method need not create a separate object for each call. Using this method is likely to have comparable cost to using the like-named field. (Unlike this method, the field does not provide type safety.)

If you are often returning empty lists in your application, Collections type-safe methods that return empty items can give you better performance.

 

Returning Optional vs null value

Returning a possibly-null value from a method is usually a bad idea. The caller of that method may not be aware that it can return null. If the caller does not handle the null case, we will have the famous NullPointerException

We already saw that returning an empty object rather than null is recommended

But in some case an “empty” object is not available? In those cases, you should return an Optional<T>.

 Optional<T> was created especially to help handling nullable return values. When the return type of a method is Optional<T>, the caller is forced into explicitly handling the null case.

Optional offers a set of helpful methods that replace the null checks.

Optional<Student> student = getStudentInfo("Jack");  

student.ifPresent(s -> print(s));

 

When to use null

There are some exceptions where using null is advisable:

  • In Data model object: where we need to map a null value to be a specific column in the database
  • When we need to clear an object: if we know that the object will never be using again, then set the object to null il better than using the clear() method.

Recent Posts