Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it bad form to return a deferred IEnumerable<T>

Tags:

c#

.net

linq

I'm curious if anyone has any rules-of-thumb or best practices on when it makes sense to return a deferred IEnumerable<T> or to call ToArray() on it before returning it from a function.

For example, as the consumer of an API I think that I would prefer for a method like IEnumerable<Widget> GetWidgets() to throw an HttpException when I call it and not have it throw when I'm enumerating the results.

public IEnumerable<Widget> GetWidgets(IEnumarable<int> widgetIds) {
    return widgetIds.Select(id => GetWidgetFromWidgetWebService(id));
}
like image 441
joshperry Avatar asked Dec 18 '12 20:12

joshperry


2 Answers

I always prefer returning a deferred IEnumerable<T> when there are not significant side effects of it being deferred. If the enumerable is based on an internal collection that may likely change, for example, I would prefer to evaluate it first.

However, if the enumerable is being computed, etc, then I would typically defer it.

like image 165
Reed Copsey Avatar answered Nov 15 '22 17:11

Reed Copsey


In case your enumerable can be practically expected to throw, eagerly evaluate it (if at all possible). You don't want the error to occur at a remote place that is unrelated to the cause of the error. You want the error right where it was caused.

After all, the method did not complete what its name advertises, so it should throw.

I usually change the return type to IList<T> in such cases to document that it executes eagerly.

like image 34
usr Avatar answered Nov 15 '22 16:11

usr