Friday, December 18, 2009

The design flaw of foreach

The foreach loop contruct in C# is very useful, but it has one major design flaw. The design flaw I'm thinking of is the NullPointerException it throws when it's given a collection that is null.
I do realize that it makes sense to throw an exception when no input is provided. The problem is that I have never seen an application that expects an exception from the foreach contruct.
With foreach you must know that the collection is set, or wrap the whole thing in a check for null. This adds an extra codeblock to your code.

I have created an extension method for collections so I can avoid the extra codeblock and do something like this:

Arguably, the real problem is GetObjects() returning null, when an empty Collection would be the usual way of saying "I have no content, but all is good and well". Returning null rather indicates an invalid operation or exceptional circumstances.

Thus don't think trying to iterate over null should silently fail, but give indication of an error, as the intention of "there just isn't anything there" is already better expressed by the empty list.

My intend was to use this on domain models. With domain models I would say the focus is on whether a collection contains elements or not... whether the collection is null or just empty often means the same thing.