Friday, June 6, 2008

The Dark Side of Extension Methods

In my quest to find a suitable generic update method for a generic LINQ Data Access class I have found a decent amount of code and even more theories (sans code).  Some good, some verbose, and a lot bad.  It seems that Extension Methods are a fan favorite for just about everything nowadays and I wasn't suprised to see Extension Methods being used for LINQ to SQL updates.

In reading about Extension Methods I have heard good and bad feedback.  The good usually involves the convenience of bypassing a utility class and the bad involving code readability / maintability.  Forgive me for I am the William Hung of LINQ as I have had no formal training in this arena, but IMHO Extension Methods are a pain-in-the-ass when ExtensionMethodA returns the result of ExtensionMethodB which depends on the output of ExtensionMethodC which ..... Here is an example of what I am talking about in pseudo-code:

public static bool Update<T>(this Table<T> table, T instance) where T: class
{
   try
   
{
      // do stuff here with parameters...
      
return table.Foo() > 0;
   }
   catch (Exception)
   {
      return false;
   }
}

public static int Foo<T>(this Table<T> table) where T: class
{
   return table.GetEnumerator().Bar();
}

public static int Bar<T>(this IEnumerator<T> e) where T : class
{
   return 1;

Horrible example yes and for that I apologize.  Hopefully you see where I am going with this and that if you are given a similar codebase it can be quite confusing.  When I first heard of extension methods I though they were for simple utility tasks such as outputting a decimal value as a dollar amount (again, doesn't REALLY warrant an extension method but...):

public static string PrintWithDollarSign(this decimal input)
{
   return input.ToString("c");
}

Simple. Effective. Here's how you would use:

Console.WriteLine(instance.Price.PrintWithDollarSign());

Cheap. No frills.  I could have just bypassed this extension method altogether but it provides a very "Hello World"'y introduction to extension methods for those of you not hip to them.  In my previous example if you had an object with a decimal property and the value was 5.00 the output would be $5.00. Easy.

Anyone care to chime in on extension methods relying on other extension methods? I'd love to get some feedback.

No comments:

Post a Comment