Best Practices: Avoid Returning Null
June 9, 2010 by Frank Salinas · 5 Comments
I recall the first oddity that struck me about Java programming is that it seems common practice to test returned objects for null. I find it frustrating and inefficient to scatter if conditions throughout my code just to see if I have a valid object instance returned.
Receiving null is confusing. When you make a function call and the result is null what does it mean? Was the data not found? Was there an exception in the function that was silently swallowed resulting in the return of a null object? You’re not really sure if null is an expected return value. If no exception is thrown then you just kind of assume that null is a valid return value. However, you can’t really do anything with the returned null object so what do you do now?
Here are a couple of alternatives to returning null:
Use the Empty Collection Methods
If you are working with returning collection objects from your function you should return an empty collection rather than a null object. This is very easy to do with the Collections class. There are three static methods available:
- Collections.emptyList()
- Collections.emptySet()
- Collections.emptyMap()
An empty List is easily instantiated for return as shown here:
List<String> myList = Collections.emptyList();
Returning an empty List eliminates the required check for null by the function caller. Now instead of having code which looks like this:
List<String> names = getNames();
if(names != null) {
for(String name : names) {
System.out.println(name);
}
}
You can simply write the following without worrying about a NullPointerException:
List<String> names = getNames();
for(String name : names) {
System.out.println(name);
}
This second example is much cleaner, easier to read and understand. Returning empty Collections is much safer as well since it avoids the potential run time exception: NullPointerException.
An unchecked exception represent defects in the program (bugs) - often invalid arguments passed to a non-private method. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes : “Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program’s logic and cannot be reasonably recovered from at run time.” [1]
Certainly an empty collection is not a bug! So lets just return an empty collection rather than a null reference. In addition, testing for an empty collection is a lot more intuitive than testing for null.
List<String> names = getNames();
if(names.isEmpty()) {
//throw an Exception
//or do something else
//or do nothing at all
}
Throw an Exception
It’s perfectly acceptable to throw a custom checked exception alerting the calling client that the requested object cannot be populated or retrieved. This approach is much more revealing and forces the calling client to handle the potential problem. It also eliminates the need to check the returned object for null.
A checked exception is guaranteed to be handled so you gain more control over your program. A RuntimeException may or may not be handled by the caller and will bubble up until either it is caught or reaches the top of the caller chain.
Conclusion
Nulls are useful under certain conditions when null values are expected. However, for the above conditions with collections and data retrieval I feel it has been abused. Use the empty collection and avoid returning null objects whenever possible. It will make code cleaner, easier to read and debug.
Citations:
1. “checked versus uncheck exceptions” JavaPractices.com. 2010 Hirondelle Systems. 6 June 2010 <http://www.javapractices.com/topic/TopicAction.do?Id=129>
No related posts.