Friday, September 2, 2011

when to use chaining

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:

No comments:

Post a Comment