Visual Studio Refactoring And Encapsulation

I love the refactoring support in MS Visual Studio.  It makes certain things like field encapsulation incredibly easy.

For instance, thanks to its origins in C, most of the Basternae 3 codebase doesn’t have encapsulation yet.  This means that there are tons of class member variables declared like this:

public string _keyword;

Setting the _keyword member variable to private and creating a property named Keyword with getters and setters that reference the _keyword variable would take about 30 seconds.

With Visual Studio it’s easier:  Just right-click on the variable and select “Encapsulate Field”.  It will come up with a reasonable property name and automatically generate the code and set the variable to private.

Pretty nice, but nothing to write home about.

But, here’s the magic:

All references to that variable in code are AUTOMATICALLY changed to refer to the property.  If that member variable was used in 50 different places, Visual Studio just saved you the trouble of making 50 different changes or doing a search-and-replace that may or may not get everything on the first try.

Of course, this doesn’t automatically update any XML files that have been saved using the old variable name.  To take care of that you can do one of two things.

1. Do a search and replace in every XML file that your class would have been serialized to and hope you didn’t miss one.
2. Use the XmlElementAttribute on your property to map the saved attributes to your new type:
[XmlElement(“_keyword”)]
public string Keyword
{

#2 is obviously safer and easier, especially since it doesn’t require changes to existing data.  Of course, your data files might be clearer to read if they used the exact property names, but do you want to go through the trouble?  Likely not.