Today I experimented with an extension method that Kar-Khan wrote for casting an IEnumerable<T> to a DataTable. It starts out like so...
public static class GenericExtensions
{
public static DataTable ToDataTable<T>(this IEnumerable<T> collection)
{
...and may be used as such:
var foo = getIEnumerableOfSomeVariety();
var bar = foo.ToDataTable();
Kar-Khan recommended against doing this:
var bar = getIEnumerableOfSomeVariety().ToDataTable();
Why? Why not chain the two concerns together as is done here? Kar-Khan asserted that, in the case of his extension method, if the IEnumerable is null there will be trouble! (Expect an exception.) The code above comes from a (predictable) test class, but arguably this is merited:
var foo = getIEnumerableOfSomeVariety();
DataTable bar = new DataTable();
if (foo != null) bar = foo.ToDataTable();
It is good policy to not go nuts with chaining for this reason. You have to consider if there is a weak link in a chain. Exceptions:
- lambdas replacing foreach loops
- IQueryable build-ups (The whole of the chain will ultimately become one query. The chains, in these scenarios, should not be thought of as sequential collections of progressive steps.)
No comments:
Post a Comment