Skip navigation

Cure Code Bloat

Refactoring in Visual Studio 2005

ControlFreak

LANGUAGES: VB.NET | C#

ASP.NET VERSIONS: 2.x

 

Cure Code Bloat

Refactoring in Visual Studio 2005

 

By Steve C. Orr

 

Successful software systems grow larger and more complex over time. Sometimes they grow gracefully; but all too often, they grow in fits and spurts that result in unsightly code bulges. Perhaps you ve become the victim of a monster piece of code that s seemingly grown out of control: functions that contain hundreds of lines of code, poorly named variables, and classes that have sprouted functions that clearly belong elsewhere.

 

We like to think of ourselves as good designers who wouldn t let such a thing happen in the first place, but sometimes business realities interfere with this vision. Perhaps time constraints didn t allow for a proper design up front and a hack simply had to get out the door A.S.A.P. Or perhaps you ve inherited code from another developer and found it to be in less-than-ideal condition.

 

No matter how you got there, you re stuck with complicated code that isn t very maintainable and you ve been assigned to build upon it. Now what do you do? I know you re tempted to rewrite it; sometimes that is the best thing to do but not usually. More often than not, refactoring will provide the best return on your investment of time and effort.

 

Refactoring 101

Refactoring is the art of reorganizing the internal structure of code without changing its public behavior. There are many ways one can go about refactoring code. One of the simplest examples would be to rename single-character private variables, instead giving them more descriptive variable names. This increases the code s readability and maintainability without altering the functionality of the code, or changing its public interface.

 

But how? You could find each such variable by manually looking through the code and changing every variable name one at a time. While this may work for tiny fragments of code, it becomes time consuming and error prone for larger blocks of code. You could use a find/replace text tool like the one that s always been in Visual Studio. This can certainly be useful, but must be used with caution so that similarly named variables aren t also altered accidentally.

 

Refactoring in C#

Gratefully, C# developers have great new refactoring tools in Visual Studio 2005 under the new Refactor dropdown menu (shown in Figure 1).

 


Figure 1: Visual Studio provides a rich set of refactoring tools for C# developers.

 

Selecting Rename from the Refactor dropdown menu brings up the dialog box shown in Figure 2. Simply type the new name for the selected variable and you re one click away from having the variable intelligently renamed everywhere that s applicable. This is much better than a standard text search-and-replace, which can cause similar variables to be accidentally renamed if you re not careful. The rename refactoring process considers the scope and precise name of the variable and will not rename similarly named variables anywhere else in the project. In case you don t at first believe it will perform that perfectly, you have the option of previewing the changes before they are made. You also have the option to replace any mention of that variable within code comments or strings instead of only in the executable code. The rename refactoring process can save time and help ensure all variables get named consistently throughout a project so code will be higher quality and more maintainable.

 


Figure 2: Visual Studio provides intelligent variable renaming functionality that takes into consideration the scope of the variable.

 

Encapsulate Field

Another useful refactoring process from the Refactor dropdown menu is Encapsulate Field. This will turn a simple variable declaration into a public property. This can save a significant amount of typing. For example, look at the following public field declaration:

 

private string _StatusBar;

 

After selecting it and choosing Encapsulate Field from the Refactor menu, the full property syntax is automatically generated for it:

 

public string StatusBar

{

   get { return _StatusBar; }

   set { _StatusBar = value; }

}

 

Extract Method

The Extract Method process, also available off the Refactor dropdown menu shown in Figure 1, is useful for situations when a function has become too large for its own good. A general rule of thumb that many developers go by is that if a function is too large to fit entirely on the screen at one time, it should be broken down into smaller functions. Ah, but that s easier said than done once a function has turned to spaghetti. Trying to do this manually involves tracking down variable declarations, ensuring all the proper variables get passed to the new child functions, and making sure all relevant values that are modified in the child functions are returned as needed to the parent function. This is a tedious chore indeed; as such, all too often it is left undone.

 

This is why the Extract Method refactoring process is so valuable. It does all the boring work for you. Simply select the block of code that you d like to extract into a child method and choose Extract Method from the Refactor menu. After typing in the name for the new function and clicking the OK button, the code will be automatically extracted into this new function (which will appear just below the parent function in the code editor). Any necessary in and out parameters are automatically created it s as simple as that. Now you have no excuse for untidy code.

 

Keep in mind that this (like most refactorings) won t break any code that references the original method because its original interface hasn t changed.

 

Parameter Refactoring

Many functions accept multiple parameters, and their parameters can grow awkwardly over time. Perhaps you prefer to order the parameters according to their importance, or perhaps you prefer to order them alphabetically. No matter what reasoning you have for such matters, it is best to be consistent. The Reorder Parameters refactoring helps you accomplish this goal. The dialog box shown in Figure 3 lists the parameters of the selected method and lets you move their order up and down with the arrow buttons. The reordering functionality is smart enough to change any calling code within the solution that references that method so the parameters stay in sync everywhere throughout the code and nothing breaks.

 


Figure 3: C# s Reorder Parameters functionality is intelligent enough to adjust calling code so that parameters stay in sync everywhere and nothing breaks.

 

The Remove Parameters refactoring can also be occasionally useful. This functionality is also smart enough to adjust any code that calls the method so that the proper parameters are passed to the function. Use this refactoring more cautiously than the others though, because removing a parameter upon which the function relies could cause compilation errors.

 

What about VB?

All that C# refactoring stuff sure looks neat, but what about all the VB developers out there? Well, there s good news and bad news. The bad news is that only rename refactoring is included with Visual Studio 2005 for VB developers. No other refactoring capabilities are included by default for VB. Nobody was more upset at Microsoft about this than me.

 

But before all you C# developers start getting a big head about your superior tools, I m happy to say that, in the end, Microsoft came through for VB developers too, with the help of a company called Developer Express, Inc. They partnered with Microsoft to develop a free high-quality refactoring plug-in for VB 2005 developers: Refactor! for Visual Basic 2005 provides refactoring capabilities that are superior to C# s built-in refactoring features in virtually every way. Most notably, it provides more refactoring types, a more intuitive user interface, and better performance. While the standard C# refactoring dialog boxes are solid and utilitarian in nature, the free refactoring add-in for VB might just leave you in awe when you see how intuitively things seem to just pop into place at all the right moments. In fact, you re not likely to see any dialog boxes at all.

 

To avoid any potential confusion you should know that Developer Express also has a professional version of Refactor! (which is not free) that includes even more refactorings, C# support, Visual Studio 2002 and 2003 support, and more.

 

Figure 4 shows how much flashier VB s refactoring support is than C# s. Relevant code is highlighted, informative windows pop up intuitively, and arrows and animations appear to make it clear which blocks of code will be moved, and where. Solid underline icons appear beneath code that can be refactored, and interacting with these brings up SmartTags that list all currently applicable refactoring possibilities. Alternatively, you can right click on any piece of code to bring up pertinent refactoring options.

 


Figure 4: VB s refactoring support is much flashier than C# s and it doesn t rely on utilitarian dialog boxes. Instead, SmartTags, animations, and other helpful windows pop up intuitively, supplying instant code improvements.

 

While Visual Studio 2005 provides C# with six refactoring capabilities, the free Refactor! for Visual Basic 2005 plug-in includes around two dozen refactorings, many of which are quite useful and encourage good programming practices.

 

Some of the highlights include the Introduce Constant refactoring, which instantly converts magic numbers into constants; the Move Initialization to Declaration refactoring, which combines a variable s initial assignment with its declaration, as illustrated in Figure 4; and Split Initialization from Declaration refactoring, which does the opposite. If you choose to register the plug-in with Developer Express, you ll have access to several additional refactoring types (see Figure 5).

 

Refactoring Type

Visual Studio

C# Support

Refactor! For

VB 2005 Support

Rename

X

X

Reorder Parameters

X

X

Extract Method

X

X

Extract Property

 

X

Encapsulate Field

X

X

Remove Parameters

X

 

Promote Local Variable to Parameter

X

 

Create Overload

 

X

Surrounds With

 

X

Reverse Conditional

 

X

Simplify Expression

 

X

Introduce Local

 

X

Introduce Constant

 

X

Inline Temp

 

X

Replace Temp with Query

 

X

Split Temporary Variable

 

X

Move Initialization to Declaration

 

X

Split Initialization from Declaration

 

X

Move Declaration Near Reference

 

X

Create Method Contract *

 

X

Use String.Format *

 

X

Rename Local *

 

X

Safe Rename*

 

X

More future VB refactorings... *

 

X

*Requires free registration with Developer Express, Inc.

Figure 5: Refactoring support for C# and VB.

 

Healthy Code Is Good Code

As successful software projects age and expand, some refactoring is usually necessary to prune code trees so they can continue to grow healthily in the long term. Refactoring tools help to simplify this chore, making tune-ups a breeze. Refactoring tools promote good programming practices by making it easy to elevate code into a more maintainable syntax and improved design. As developers and companies refine their development standards, tools such as these can make it simple to retrofit existing code to conform to the new syntactical standards without risking the introduction of bugs.

 

Refactoring tools are not magic. It still takes careful thought and planning to decide what code should be refactored and in which ways. However, refactoring tools can help spur that thought process and they certainly take the tedium out of making the specific changes. It s even rather fun to watch these tools do work in seconds that otherwise could take many hours to do manually or perhaps never even gotten done at all.

 

Refactoring tools have matured dramatically in the last few years. While the tools outlined here are some of the best around, they still don t come close to providing every different kind of refactoring that is conceptually possible. Refactoring is a deep topic, and there are many books written on the subject. I encourage you to dig deeper to find even more ways to refactor your code.

 

Bloated code may never disappear from the world completely, but now every developer has a fighting chance. Now you have no excuse for untidy code, because these tools will help clean it up in a flash.

 

Download Refactor! for Visual Basic 2005 directly from Microsoft from http://msdn.microsoft.com/VBasic/Downloads/Tools/Refactor/.

 

Steve C. Orr is an MCSD and a Microsoft MVP in ASP.NET. He s been developing software solutions for leading companies in the Seattle area for more than a decade. When he s not busy designing software systems or writing about them, he can often be found loitering at local user groups and habitually lurking in the ASP.NET newsgroup. Find out more about him at http://SteveOrr.net or e-mail him at mailto:[email protected].

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish