Imagine a method which takes an object as a parameter and check with a for each loop for lets say some other values inside of some collection, which can be found/filtered according to the passed in argument. Is it a good practice to check at the beginning of the function for null pointer and return immediately an empty collection or null pointer, or is it better to just leave out the null pointer checking, as for each loop takes care of it, but the function will need more time to execute (because of the whole for each iteration). And lets say that this collection isn't big (not that much time consuming).
public ArrayList<Foo> find(Bar bar) {
if (bar == null) { // get rid of these part?
return null; //
} //
ArrayList<Foo> foos = new ArrayList<Foo>();
for (Foo f: Foo.values()) {
if (f.someBarCollection.contains(bar)) {
foos.add(f);
}
}
return foos;
}
I think It's better to check for null and return immediatelly if you know that It's a waste of time doing any further actions, because you know they're not needed. So I'm favouring semantics at the expense of a shorter code, to make things unambigous.
EDIT: Let me elaborate a bit further. The result of the function is the same with OR without the null checking part. The question is just, should I check It anyway, just for the sake of better expression (and a bit of performance gain, but this is not a problem), but the code will be longer (because of the added checking)?