Monday 24 August 2009

Extension Method Usage

If you are like me, once you have the Big Extension Method Realisation you tend to go overboard on their use.  This is eventually followed by the more practical Extension Method Usage Realisation.  This second realisation puts Extension Methods into perspective.

For example, you could quite easily create an extension method like this:
public static bool IsNull(this object thisObject)
{
return thisObject == null;
}
This method can replace
if(myObject==null)

with...

if(myObject.IsNull())

But is it worth it?  Is there anything wrong with myObject==null?  Of course not.  So why change it or replace it with an extension method.  It adds no new functionality, just a change of syntax.
Additionally, you will often collect your extension methods and place them in a common assembly.  Use of the above extension method creates an dependency on this assembly.  But what does it buy you?  I would argue, nothing.  So, lose it.
From my experience in working with extension methods, I've found the most valuable to be methods that supply missing functionality or ones that encapsulate often repeated code. 
An example of this is checking if a collection contains any items, kind of like a cousin of String.IsNullOrEmpty.  For me, this is a prime candidate for an extension method, and should have been included in the IList interface (IMHO).

public static bool HasItems(this IList collection)
{
return collection != null && collection.Count > 0;
}
So we reduce
if(myCollection!=null && myCollection.Count>0)

to a clean and simple

if(myCollection.HasItems())

I know there is not a shortage of resources on the web regarding extension methods.  However, after working with them for a few years, I have managed to collect a few "must have" extension methods, which I will be posting over time.

No comments: