July 03, 2006 12:07 AM

Cure Code Bloat

Refactoring in Visual Studio 2005
DevConnections
Rating: (0)

ControlFreak

LANGUAGES:VB.NET | C#

ASP.NETVERSIONS: 2.x

 

Cure Code Bloat

Refactoring in Visual Studio 2005

 

 

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

 

We like to think of ourselves as good designers who wouldn?tlet such a thing happen in the first place, but sometimes business realitiesinterfere with this vision. Perhaps time constraints didn?t allow for a properdesign up front and a hack simply had to get out the door A.S.A.P. Or perhapsyou?ve inherited code from another developer and found it to be in less-than-idealcondition.

 

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

 

Refactoring 101

Refactoring is the art of reorganizing the internalstructure of code without changing its public behavior. There are many ways onecan go about refactoring code. One of the simplest examples would be to renamesingle-character private variables, instead giving them more descriptivevariable names. This increases the code?s readability and maintainabilitywithout altering the functionality of the code, or changing its publicinterface.

 

But how? You could find each such variable by manuallylooking through the code and changing every variable name one at a time. Whilethis may work for tiny fragments of code, it becomes time consuming and errorprone for larger blocks of code. You could use a find/replace text tool likethe one that?s always been in Visual Studio. This can certainly be useful, butmust be used with caution so that similarly named variables aren?t also alteredaccidentally.

 

Refactoring in C#

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

 


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

 

Selecting Rename from the Refactor dropdown menu brings upthe dialog box shown in Figure 2. Simply type the new name for the selectedvariable and you?re one click away from having the variable intelligentlyrenamed everywhere that?s applicable. This is much better than a standard textsearch-and-replace, which can cause similar variables to be accidentallyrenamed if you?re not careful. The rename refactoring process considers thescope and precise name of the variable and will not rename similarly namedvariables anywhere else in the project. In case you don?t at first believe itwill perform that perfectly, you have the option of previewing the changesbefore they are made. You also have the option to replace any mention of thatvariable within code comments or strings instead of only in the executablecode. The rename refactoring process can save time and help ensure allvariables get named consistently throughout a project so code will be higherquality and more maintainable.

 


Figure 2: Visual Studio providesintelligent variable renaming functionality that takes into consideration thescope of the variable.

 

Encapsulate Field

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

 

private string _StatusBar;

 

After selecting it and choosing Encapsulate Field from theRefactor 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 Refactordropdown menu shown in Figure 1, is useful for situations when a function hasbecome too large for its own good. A general rule of thumb that many developersgo by is that if a function is too large to fit entirely on the screen at onetime, it should be broken down into smaller functions. Ah, but that?s easiersaid than done once a function has turned to spaghetti. Trying to do this manuallyinvolves tracking down variable declarations, ensuring all the proper variablesget passed to the new child functions, and making sure all relevant values thatare modified in the child functions are returned as needed to the parentfunction. This is a tedious chore indeed; as such, all too often it is leftundone.

 

This is why the Extract Method refactoring process is sovaluable. It does all the boring work for you. Simply select the block of codethat you?d like to extract into a child method and choose Extract Method fromthe Refactor menu. After typing in the name for the new function and clickingthe 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 necessaryin and out parameters are automatically created ? it?s as simple as that. Nowyou have no excuse for untidy code.

 

Keep in mind that this (like most refactorings) won?tbreak any code that references the original method because its original interfacehasn?t changed.

 

Parameter Refactoring

Many functions accept multiple parameters, and theirparameters can grow awkwardly over time. Perhaps you prefer to order theparameters according to their importance, or perhaps you prefer to order themalphabetically. No matter what reasoning you have for such matters, it is bestto be consistent. The Reorder Parameters refactoring helps you accomplish thisgoal. The dialog box shown in Figure 3 lists the parameters of the selectedmethod and lets you move their order up and down with the arrow buttons. Thereordering functionality is smart enough to change any calling code within thesolution that references that method so the parameters stay in sync everywherethroughout the code and nothing breaks.

 


Figure 3: C#?s Reorder Parametersfunctionality is intelligent enough to adjust calling code so that parametersstay in sync everywhere and nothing breaks.

 

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

 

What about VB?

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

 

But before all you C# developers start getting a big headabout your superior tools, I?m happy to say that, in the end, Microsoft camethrough for VB developers too, with the help of a company called DeveloperExpress, Inc. They partnered with Microsoft to develop a free high-qualityrefactoring plug-in for VB 2005 developers: Refactor! for Visual Basic 2005provides refactoring capabilities that are superior to C#?s built-inrefactoring features in virtually every way. Most notably, it provides morerefactoring types, a more intuitive user interface, and better performance. Whilethe 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 howintuitively things seem to just pop into place at all the right moments. Infact, you?re not likely to see any dialog boxes at all.

 

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

 

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

 


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

 

While Visual Studio 2005 provides C# with six refactoringcapabilities, the free Refactor! for Visual Basic 2005 plug-in includes aroundtwo dozen refactorings, many of which are quite useful and encourage goodprogramming practices.

 

Some of the highlights include the Introduce Constantrefactoring, which instantly converts ?magic numbers? into constants; the MoveInitialization to Declaration refactoring, which combines a variable?s initialassignment with its declaration, as illustrated in Figure 4; and SplitInitialization from Declaration refactoring, which does the opposite. If youchoose to register the plug-in with Developer Express, you?ll have access toseveral 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: Refactoringsupport for C# and VB.

 

Healthy Code Is Good Code

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

 

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

 

Refactoring tools have matured dramatically in the lastfew years. While the tools outlined here are some of the best around, theystill don?t come close to providing every different kind of refactoring that isconceptually possible. Refactoring is a deep topic, and there are many bookswritten on the subject. I encourage you to dig deeper to find even more ways torefactor your code.

 

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

 

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

 

Steve C. Orr is anMCSD and a Microsoft MVP in ASP.NET. He?s been developing software solutionsfor leading companies in the Seattlearea for more than a decade. When he?s not busy designing software systems orwriting about them, he can often be found loitering at local user groups andhabitually lurking in the ASP.NET newsgroup. Find out more about him at http://SteveOrr.netor e-mail him at mailto:Steve@Orr.net.

 

 

 

Add a Comment

There are no comments to display. Be the first one!
You must log on before posting a comment.

Are you a new visitor? Register Here

advertisement




Comments from the DevConnections Community

Join our community of development pros.

Windows problem

I all, I have a problem on my Windows Vista that began afetr the purchase of an external Hard Disk Freecom. A few days afetr the purchase I discon...

Most Recent Posts

GOOGLE LINKS
SPONSORED LINKS
FEATURED LINKS