Using Extensions: Weighing The Pros vs. Cons

Sun, Feb 15, 2009

Technology

Recently I asked a question about how to clean up what I considered ugly code.  One recommendation was to create an Extension Object that would perform the desired function and return back what I wanted.  My first thought was ‘Great! How cool are Extensions…’ but after a little more thinking I am starting to have second thoughts about using Extensions…

My main concern is that it seems like Extensions are a custom ’shortcut’ that can make it hard for other developers to follow.  I understand using an Extension can help make the code syntax easier to read, but what about following following the voice behind the curtain? 

Take for example my previous code snippet:

if (entry.Properties["something"].Value != null)
  attribs.something = entry.Properties["something"].Value.ToString(); 

Now replace it with an Extension:

public static class ObjectExtensions
{
    public static string NullSafeToString(this object obj)
    {
        return obj != null ? obj.ToString() : String.Empty;
    }
} 

and call using the syntax:

attribs.something = entry.Properties["something"].Value.NullSafeToString(); 

Definitely a handy way to go, but is it really worth the overhead of another class object?  And what happens if someone wants to reuse my code snippet but doesn’t understand Extension Objects?  I could have just as easily used the syntax with the same result:

attribs.something = (entry.Properties["something"].Value ?? string.Empty).ToString() 

So I did a little digging and found a couple of articles that talked about the pros/cons of using Extensions.  For those inclined have a look at the following links:

MSDN Extension Methods

Extension Methods Best Practice

Scott Gu: Extension Methods

It seems the decision to use Extensions is evenly divided for and against.  The main argument against using them is the difficulty in following these custom extensions during a code review/share.

I can’t really decide which is the better way to go.  Custom Extensions that do exactly what I want them to do or more displayed code to accomplish the same task?  I would be really interested in learning what ‘real’ developers think about this topic…

Comments are closed.