Is there a way to avoid null check before the for-each loop iteration starts? [duplicate]
If possible, you should design your code such that the collections aren't null
in the first place.
null
collections are bad practice (for this reason); you should use empty collections instead. (eg, Collections.emptyList()
)
Alternatively, you could make a wrapper class that implements Iterable
and takes a collections, and handles a null
collection.
You could then write foreach(T obj : new Nullable<T>(list1))
public <T extends Iterable> T nullGuard(T item) { if (item == null) { return Collections.EmptyList; } else { return item; }}
or, if saving lines of text is a priority (it shouldn't be)
public <T extends Iterable> T nullGuard(T item) { return (item == null) ? Collections.EmptyList : item;}
would allow you to write
for (Object obj : nullGuard(list)) { ...}
Of course, this really just moves the complexity elsewhere.
I guess the right answer is that: there is no way to make it shorter. There are some techniques such as the ones in the comments, but I don't see myself using them. I think it's better to write a "if" block than to use those techniques. and yes.. before anybody mentions it yet again :) "ideally" the code should be desgined such that list should never be a null