Nerdy tidbits from my life as a software engineer

Wednesday, June 10, 2009

Snippets are a Life Saver

I occasionally keep forgetting how critical snippets are to my productivity.  I actually keep a bunch of snippets on my Sky Drive so that I can port them over from one machine to another.  With the help of snippets, some incredibly tedious tasks that would normally drive me nuts with boredom can be largely skipped with automation.

There are a few major snippets that I use constantly – particularly with WPF applications.  The first is the absolutely critical Dependency Property snippet (yes, I know Visual Studio ships with one of these, but I like mine much, much more):

/// <summary>
/// Defines the $Name$Property dependency property.
/// </summary>
public static readonly DependencyProperty $Name$Property = DependencyProperty.Register("$Name$", 
    typeof($Type$), 
    typeof($Owner$));

/// <summary>
/// Gets / sets the $Name$ property.
/// </summary>
public virtual $Type$ $Name$
{
    get 
{ return ($Type$)GetValue($Name$Property); } set
{ SetValue($Name$Property, value); } }

This alone saves me hours of development time, since I don’t need to cut and paste this same code over and over again.  But today, as I was painfully filling out some code to support the INotifyPropertyChanged interface, I realized that I should really make a snippet out of it to save me time.  And so, I came up with this:

/// <summary>
/// Defines the $Name$ property value.
/// </summary>
private $Type$ m$Name$;

/// <summary>
/// Gets / sets the name of the argument.
/// </summary>
public $Type$ $Name$
{
    get
    {
        return m$Name$;
    }
    set
    {
        this.m$Name$ = value;
        this.FirePropertyChanged("$Name$");
    }
}

Of course, this assumes that you’ve defined the FirePropertyChanged method somewhere in your class, which is very simple and usually just looks like this:

/// <summary>
/// Fires the PropertyChanged event.
/// </summary>
/// <param name="propertyName">The name of the property that changed</param>
private void FirePropertyChanged(string propertyName)
{
    if (this.PropertyChanged != null)
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

So this experience has reminded me that whenever I end up doing some mindless, repetitive task over and over again, I should write a snippet for it.  Too bad the snippet editor isn’t part of Visual Studio 2008.  It’s relatively baffling that we have a built-in snippets manager, but not a snippets editor.  I should double check what we’ve got coming up in 2010…

0 comments: