| Author |
Returning null vs returning empty collection
|
Shaik Muhammad
Ranch Hand
Joined: Jul 16, 2008
Posts: 36
|
|
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
Joined: Nov 24, 2005
Posts: 14685
|
|
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.
|
[My Blog]
All roads lead to JavaRanch
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Adam Michalik
Ranch Hand
Joined: Feb 18, 2008
Posts: 128
|
|
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.
|
 |
 |
|
|
subject: Returning null vs returning empty collection
|
|
|