.NET Tips and Tricks

Blog archive

Return an Interface from Your Methods for Maximum Flexibility

If I'm writing a method that returns a collection, I can, of course, declare my method's return type using a class name, like this:

Public Function GetCustomersByCity(City As  String) Returns List(of Customer)

But by declaring my return type as class in this way, I restrict my method to only returning that class (in this example, a List). I might eventually want to rewrite the method to return some other class, but my overly-specific return type will prevent me from doing that. A much better practice is to just specify an interface name when returning a collection. That allows me to return any class I want, provided I pick a class that implements the interface I choose.

You want to choose an interface that applies to the maximum number of classes (giving you maximum flexibility in deciding what class to use), while also exposing all the functionality that someone using your method will want to use (giving your clients exactly as much flexibility as you want). There's going to be some conflict here because, presumably, the most common interface is going to be the one with the least functionality. Microsoft gives you at least three choices: IQueryable, IList and IEnumerable.

From the point of view of supplying functionality, if you just want to give your users the ability read the entries (i.e. loop through the collection with a For…Each loop or apply LINQ queries to it), any of these interfaces will do. If you want to give the application that's calling your method the ability to add or remove items from a collection, you'll want to return the IList interface (that does restrict your method to returning classes that support adding and removing items, which means, for example, that you won't be able to return an array from your method).

From the point of view of giving yourself maximum flexibility, IEnumerable is your best choice (both IList and IQueryable inherit from IEnumerable). A quick, non-exhaustive survey suggests to me that IQueryable is your most limiting choice (you can't return a List from a method with a return type of IQueryable). But performance matters also: IQueryable is the right choice for LINQ queries running against Entity Framework, because IEnumerable doesn't support server-side processing or deferred execution the way IQueryable does.

Summing up, my current best advice is: Use IList if your clients need to change the collection; IQueryable if your method is returning an Entity Framework result; IEnumerable for everything else.

I bet I'm going to get comments about this advice …

Posted by Peter Vogel on 06/28/2014


comments powered by Disqus

Featured

Subscribe on YouTube