I often come across the following scenario. I have a method that returns a list of elements that satisfy a specific criterion. If there is no elements that match a specific criterion, which is the better value that the method can return? null or a empty list.
I personally feel that returning null causes the caller methods to check for null everytime the method is called. Also, returning empty means unnecessarily a collection is created which will never contain any element in it.
I remember reading in Effective Java that you should return an empty collection, to avoid unnecessary null checks. The caller would check for an empty collection only if needed. You can still loop through an empty collection without getting a NullPointerException. I don't see this as a performance issue.
If you document your methods well (using Javadoc), returning either null or an empty collection should not be an issue.
Christophe Verré wrote:I remember reading in Effective Java that you should return an empty collection, to avoid unnecessary null checks.
Consider this usage of your API: a client calls your method to get the collection and wants to perform some tasks on each element of it. Or to check the size. Returning an empty collection is perfectly consistent with returning a collection of any other size - the size() method will return 0, the iteration will do nothing. No surprise for the client. Returning null will be much more surprising and would require additional workload on the client's side. I remember Josh Bloch saying in Effective Java or somewhere else that you should not surprise the user of your API - I agree with him 100 % If you're concerned with unnecessary empty collection creation, Rob's tip is a way to go.