• Post Reply Bookmark Topic Watch Topic
  • New Topic

Returning null vs returning empty collection  RSS feed

 
Shaik Muhammad
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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.

Please suggest a better return value.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shaik Muhammad wrote:Also, returning empty means unnecessarily a collection is created which will never contain any element in it.

Please suggest a better return value.

Check out java.util.Collections - the emptyXXX methods are just what you're looking for. Unmodifiable, empty list, set and map that only are created once, and then reused when needed.
 
Adam Michalik
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!