Prefer empty collection to null is a basic java principle that stems from Effective java Item 43: return empty arrays or collections, not nulls. There are a few reasons to support it:
- Handling null sucks
- Code readability suffers
- It is error prone. Developers are lazy and the consumer might forget to write code to handle null.
- Method signature says it returns a collection, null is not a collection
Using and avoiding nulls is outlined in guava documentation but if you have looked at code where folks don't follow this rule, it gets ugly fast. Not only do you deal with
NullPointerException, you deal with verbose and extra code you have to maintain. A few examples I see during code reviews:
Return an empty collection
In practice you should return the same immutable empty collection every time you return an empty collection. We put together examples for reference, return empty list, return empty map, return empty set, return empty enumeration, return empty list iterator, return empty iterator, return empty sorted set and return empty sorted map. To create consistency and maintainability of code, Guava and Apache have implemented a comparable way to return an empty list. Lets take a look at returning an empty list:
Exception to the rule
The goal is to handle the null to empty collection as soon as you can and there is no reason that you should ever code a method that returns a collection or array to return null. There will be times when you encounter a method returning null and the right thing to do is to go fix it - don't be lazy. Since most don't have a team dedicated to refactoring code, a well documented code base or a management staff that fully supports code quality there are a few ways to handle it.