Search code examples
c#ienumerableilistn-tier-architecture

IEnumerable<T> as return value, deferred execution and N-tier applications


First, I do not consider this question be the dup of these SO questions:

Should I always return IEnumerable<T> instead of IList<T>? and IEnumerable<T> as return type

As we all know ont of the main purposes of introducing several tiers is to decrease coupling.
We must define some interface for data access and our BL should not care about the details of DAL implementation. If mentioned interface returnes IEnumerable<T> BL does not know whether it is just a static IEnumerable or something that has deferred execution. At the same time this particular detail can affect perfromance considerably and requires different coding depending on the implementation.
Well, it is possible to call .ToList() for each IEnumerable in situations when we are going to iterate collection several times. But this decreases perfromance for static collections because of unnecessary new list instantiation.

So I'm trying to understand which approach is better.
More universal and potentially less performant vs More coupled-more performant. I guess, there's no silver bullet but it could be other approaches I've missed.


Solution

  • If it's important, conceptually, for the caller to know that the return type of the method is a List and not an IEnumerable (for example, to know that there will be no negative consequences for iterating it multiple times), then you should return a List. The point of returning the interface instead is a way of saying, "It doesn't matter what the implementation is." If the implementation does matter, then don't use the interface (in that specific situation).