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!