C# – Should Empty Collections Be Accepted in Methods That Iterate Over Them?

ccollectionsexceptionsparameters

I have a method where all logic is performed inside a foreach loop that iterates over the method's parameter:

public IEnumerable<TransformedNode> TransformNodes(IEnumerable<Node> nodes)
{
    foreach(var node in nodes)
    {
        // yadda yadda yadda
        yield return transformedNode;
    }
}

In this case, sending in an empty collection results in an empty collection, but I'm wondering if that's unwise.

My logic here is that if somebody is calling this method, then they intend to pass data in, and would only pass an empty collection to my method in erroneous circumstances.

Should I catch this behaviour and throw an exception for it, or is it best practice to return the empty collection?

Best Answer

Utility methods should not throw on empty collections. Your API clients would hate you for it.

A collection can be empty; a "collection-that-must-not-be-empty" is conceptually a much more difficult thing to work with.

Transforming an empty collection has an obvious outcome: the empty collection. (You may even save some garbage by returning the parameter itself.)

There are many circumstances in which a module maintains lists of stuff that may or may not be already filled with something. Having to check for emptiness before each and every call to transform is annoying and has the potential to turn a simple, elegant algorithm into an ugly mess.

Utility methods should always strive to be liberal in their inputs and conservative in their outputs.

For all these reasons, for God's sake, handle the empty collection correctly. Nothing is more exasperating than a helper module that thinks it knows what you want better than you do.