What is the best way to guard against null in a for loop in Java?
This seems ugly :
if (someList != null) {
for (Object object : someList) {
You could potentially write a helper method which returned an empty sequence if you passed in null:
public static Iterable emptyIfNull(Iterable iterable) {
return iterable == null ? Collections.emptyList() : iterable;
}
Then use:
for (Object object : emptyIfNull(someList)) {
}
I don't think I'd actually do that though - I'd usually use your second form. In particular, the "or throw ex" is important - if it really shouldn't be null, you should definitely throw an exception. You know that something has gone wrong, but you don't know the extent of the damage. Abort early.