
Season's greetings!
We're halfway through my
X-mas carol describing how
Refactor! Pro
can be used to leverage the new features of
Visual Studio
2008. Today, I'm sharing a little more
Refactor! Pro
love by demonstrating a refactoring that literally can save minutes of
menial
coding. That's right, minutes. Interested? OK, just let me
clear my voice...
"On the seventh day of X-mas my true love (DevExpress)
gave to me..."
Create Backing Store
A couple of days ago, I showed how
Refactor! Pro
can transform properties into
C#
3.0 Auto-Implemented Properties. However, sometimes the opposite is needed.
We need a way to convert from an auto-implemented property to a standard
property and field.
Consider the following code:
using System;
using System.Drawing;
namespace TwelveDaysOfXmas
{
class Present
{
public Color Color1 { get; set; }
public Color Color2 { get; set; }
}
}
Suppose that we want to add logic to both the Color1 and Color2
properties to ensure that they can't be set to the same value. Now, imagine how
much effort that would take. An awful lot of keystrokes are needed to get to the
code below.
using System;
using System.Drawing;
namespace TwelveDaysOfXmas
{
class Present
{
private Color m_Color1;
public Color Color1
{
get { return m_Color1; }
set
{
if (m_Color2 == value)
return;
m_Color1 = value;
}
}
private Color m_Color2;
public Color Color2
{
get { return m_Color2; }
set
{
if (m_Color1 == value)
return;
m_Color2 = value;
}
}
}
}
Fortunately,
Refactor! Pro provides a refactoring, called Create Backing Store, which
converts an auto-implemented property into a standard property with a field
backing store. In other words, it transforms this...
public Color Color1 { get; set; }
...into this.
private Color m_Color1;
public Color Color1
{
get
{
return m_Color1;
}
set
{
m_Color1 = value;
}
}
That's pretty close to what we want. With the help of two other refactorings,
Introduce Setter Guard Clause and Collapse Accessor, we can continue to
manipulate the property to get the code below.
private Color m_Color1;
public Color Color1
{
get { return m_Color1; }
set
{
if (m_Color1 == value)
return;
m_Color1 = value;
}
}
Now we just have to make a minor edit to the guard clause and we're done.
View Screencast of
These Refactorings in Action!
And that concludes my verse for today. Remember that the features I'm showing
you are available for download this very second. So, if you're
tired of waiting for
<whisper>the
other tool</whisper>
to get its act together,
Refactor! Pro
can have you running laps through
Visual Studio
2008 in no time.