pierrotlefou
pierrotlefou

Reputation: 40721

return nothing , using array == null or array.length == 0?

Supposing I have a function with following signature:

Foo[] getSomeFoos() 
{
      //return null         --- option A 
      or 
      //return new Foo[0];  --- option B
}

What is the recommended practice to return the value indicating there is no elements returned? Any pros or cons for each option?

Upvotes: 3

Views: 4516

Answers (5)

barrowc
barrowc

Reputation: 10679

From Effective Java (2nd ed) - item 43: return empty arrays or collections, not nulls

In summary, there is no reason ever to return null from an array- or collection-valued method instead of returning an empty array or collection

Upvotes: 0

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

I prefer zero-size array.

It's safer(avoid NPE) and easier(no need null check).

Upvotes: 0

jjnguy
jjnguy

Reputation: 138874

If your method GetSomeFoos() actually 'found' 0 elements, then it should return new Foo[0].

If there was some sort of error, you should throw an Exception.

The reason is because users shouldn't have to look for nulls:

for (Foo f: GetSomeFoos()) {
    // do stuff
}

In the above case, if GetSomeFoos returned null, a user will have to deal with an NullPointerException. But, if you return an empty array, the code will never enter the loop, and the user will not have to deal with an exception.

Upvotes: 11

Mike Baranczak
Mike Baranczak

Reputation: 8374

Returning null is more efficient, since you avoid the overhead of creating a new array or collection object. It's true that you then have to add a null check at the point where you use the function's output, but the overhead for that (in Java and almost all languages) is negligible. I also think that checking for null is a good habit to get into, especially when dealing with third-party libraries.

The downside is that you make the code more verbose.

If you do return an empty array, you can mitigate the performance hit by re-using the same object. Create an immutable constant, and return that:

private static final String[] EMPTY = {};

Or:

private static final List<String> EMPTY = 
    Collections.unmodifiableList(new ArrayList<String>());

Upvotes: 0

Dead Programmer
Dead Programmer

Reputation: 12575

Whether to return null or empty object entirely depends on the method usage. If this method is called by a client and exposed as an API then throwing exception is better , but if it is used within ur package and never used by client then returning null is ok.

Upvotes: 0

Related Questions