I can be sure that 'my code' called returnlist() is never going to return null. Thus I do not do any null pointer check when I loop in the enhanced for loop. But, looking from maintenance this does not appear to be a good practice, since someone in future can modify code base inadvertantly or someone would just override this call and overridden function may not be prudent enough to return empty collections.
public class ExtendedForLoop {
public List<Integer> returnList() {
// compute.
if list == null ? Collections.emptyCollections : list;
}
public static void main(String args[]) {
for (Integer i : returnList()) {
System.out.println(i);
}
}
So making question generic, the question is intended to know best practices of where to draw the tradeoff line. I fully understand there is not defined rule for such cases, just seeking best practices.
Adding excessive checks in self written code adds clutter but ensures its safe from future modifications.
Reducing checks because 'you know it wont return null' makes code clean, but we live with risk of accidental modification.
That's what javadoc is for:
Just add:
And further if the code runs in an embedded device installed in 400.000 vehicles you may additonally null check, although you are sure. You want to avoid calling back that devices uinder all circumstances.
If it runs on one server you can rely on correct implementation.