Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator null collection

It's quite common that I have to check null before iterate when not sure the collection reference is null or not. Sample:

Collection<Object> collection = ...
...
if(collection != null)//troublesome
    for(Object o : collection)

Of course, I know empty collection is much better than null, but in some cases client code cannot control the nullable collection from other modules (for instance, return value from 3rd party code). So I wrote a utility method:

public static <T> Iterable<T> nullableIterable(Iterable<T> it){
    return it != null ? it : Collections.<T>emptySet();
}

In client code, no need to check null any more:

for(Object o : nullableIterable(collection))
...

Do you think nullableIterable() is reasonable? Any advice? Any concern? Thanks!

like image 297
卢声远 Shengyuan Lu Avatar asked Jul 07 '12 08:07

卢声远 Shengyuan Lu


People also ask

Can iterator return null?

Overall: Java API has no mean to say if the iterator value may be null or not, unless by stating it explicitly in the documentation. In this case, nothing is stated, however good sense allows to think that a null iterator value will never be returned from Java API methods.

Can iterable be null?

Parameters declared as iterable may use null or an array as a default value. Iterable can also be used as a return type to indicate a function will return an iterable value. If the returned value is not an array or instance of Traversable, a TypeError will be thrown.

Is an iterator immutable?

An iterator is mutable: most operations on it change its state.


1 Answers

That looks good. I personally do that too. You will always get developers who would disagree with this as it is kind of defensive programming. Imagine you have a workflow or a class that is not supposed to return null. This means that getting a null from it is a bug which your code will hide as it will turn the null to an empty collection and the bug will never surface.

If you are for example writing APIs that do not support null collections then you should avoid this. If client code gives you a null collection where you do not support it, you should throw an IllegalArgumentException to let client code know that there is something wrong with the provided collection. Something like:

public void myApiNoSupportForNull(Collection<Object> collection){
   // Pre condition
   if(collection == null) 
     throw new IllegalArgumentException("This API does not support null collections!");
   //...
}
like image 109
GETah Avatar answered Oct 04 '22 12:10

GETah