Software Development

Employ refactoring via Visual Studio to write better code

Refactoring is the practice of making your code cleaner and clearer without affecting the functionality. Find out what's included in Visual Studio's Refactor menu, and discover a couple of Visual Studio add-ins that bring refactoring to the Visual Basic community.

 

One of the key aspects of Extreme Programming is refactoring, which improves code without affecting its function. The Visual Studio IDE provides refactoring features in the 2005 and 2008 versions that you can easily put into action with a mouse click. Unfortunately, this feature is only available to C# developers, but there are add-ons for developers using Visual Basic. Here's a closer look at refactoring via Visual Studio.

A simple approach

A simple explanation of refactoring is the practice of making your code cleaner and clearer while not affecting functionality. You may hear others describe it as code rewriting, but this is far from the truth. It is not rewriting since code functionality does not change. The code is working, so no rewriting is necessary -- you're just trying to make it easier to maintain and read.

After all, what developer hasn't been faced with code they did not develop? Making a change in such a situation can be a pain when the actual code is hard to understand. Refactoring makes it easier to work through these instances.

Refactoring is typically accomplished in small steps while maintaining functionality. You may refactor as you move along with development activities. The Visual Studio 2005 and 2008 development environment provide plenty of options to help with refactoring.

Using Visual Studio

Visual Studio is the de facto standard development environment for those building .NET applications. Refactoring became a feature of the tool beginning with version 2005 of the IDE. It is available via a drop-down menu called Refactor. The menu is accessible by right-clicking within code as well. The Refactor menu provides the following choices:

  • Rename: This feature allows you to easily rename items without the need to search and replace all references within the code. This menu option automatically performs the search and replace.
  • Extract Method: This feature allows you to select a block of code and extract it into a separate method. The block of code is replaced with a call to the new method. This is a great feature to use when realizing that a block of code needs to be used repeatedly.
  • Encapsulate Field: When you use this option, a public property encapsulating a field is created. It is an easy shortcut to creating properties when you realize they are necessary for certain fields within your code.
  • Extract Interface: This feature allows you to create an interface for existing code. It examines the current class and creates an interface based on its public properties and methods.
  • Promote Local Variable To Parameter: Developers often discover that a variable declared locally within a method should be a parameter passed to the method. This menu selection automates the process of moving a local variable to a method parameter. One click and the variable becomes a parameter.
  • Remove Parameters: This allows you to easily remove a parameter from a method signature. In addition, all calls to the method are altered to remove the passed parameter as well. Visual Studio provides a preview window for viewing the changes before selecting OK and making them permanent.
  • Reorder Parameters: This feature automates the reordering of parameters in a method signature. This may seem like a simple task, but it handles the reordering of parameters in all code that references the changed method.

The best way to get better acquainted with these features is to use them. Take Refactor for a test drive with your code to get an idea of how it works and notice how code is cleaned up and simplified.

Visual Basic developers

The only Refactor option available to Visual Basic developers is Rename. While this is a good feature to have, Microsoft leaves Visual Basic developers out in the cold with regards to the other features.

Visual Studio add-ins are available for bringing refactoring to the Visual Basic community. One popular product is Refactor! Pro. Another excellent Visual Studio add-in is ReSharper; it does not, however, target Visual Basic developers.

The omission of refactoring features for Visual Basic leaves me scratching my head. Microsoft proclaims it would never turn its back on the Visual Basic community, but actions speak louder than words.

Available to all developers

Refactoring code is not restricted to .NET languages. You can improve code whether it is JavaScript, HTML, Java, PHP, Perl, or any one of the numerous languages in use today. The principles of refactoring are applicable everywhere.

Who doesn't want to produce better code?

Refactoring allows developers to simplify their code to deliver cleaner and more manageable solutions without losing functionality. Thankfully, Microsoft has recognized the importance of refactoring with its inclusion in Visual Studio 2005 and 2008.

Are you employing extreme programming principles in your everyday development chores? Has refactoring helped you produce better code? Share your thoughts with the Web Developer community.

Related TechRepublic resources

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

---------------------------------------------------------------------------------------

Get weekly development tips in your inbox Keep your developer skills sharp by signing up for TechRepublic's free Web Developer newsletter, delivered each Tuesday. Automatically subscribe today!

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

39 comments
jslarochelle
jslarochelle

...to use refactoring to its full potential. The good news is that C# has a very good unit tests tool (NUnit). JS

Stan.Williams
Stan.Williams

that you probably won't program by stopping every 5 minutes to hit the refactor option. I don't think anyone, especially the author, is suggesting we do. There is a case to be made for better planning but if you can write code perfectly the first time then congrats. You are the only one I know. There was an article several weeks earlier pointing out the flaw in using OO techniques arbitrarily and how that line of thinking can cause performance loss. I'm not going to stop using oo but the point was well made and the example in the article, however simple, has probably been used thousands of times. So, use refactoring only when you know what should have been changed and want to save time by letting the IDE do it for you. I get the point. Nice article. Exactly what I've come to expect from Mr. James. Thanks.

Dauhee
Dauhee

refactoring does involve code rewriting - its not just a readability factor - its also about performance, reliability, scalability etc

Tony Hopkinson
Tony Hopkinson

but remember it's devloper's who refactor, not IDEs. If you tell it to do something really stupid it will. This is an intelligent search and replace and we all know you can do some really dumb stuff with that. As JJ says refactoring should be just obvious no matter what lifecycle and or methodology you use. Before you start have some decent unit tests in place, do a before and after it's dead easy to inadvertantly change functionality. Be very careful of Swapping one built in component or class for another, they have baggage. Dealing with exceptions. You'll be looking at the standard execution flow, everything's okey dokey then you find an unexpected exception or even worse don't get an expected one. If you are switching to or from using interfaces as opposed to class instances, be very careful about what null means. Knock on effects, have you ever caused a 'bug' from making something too fast? Last but not least if you manage to convince the business heads that refactoring is good for them, without the use of incriminating photos or a gun, please let me know how.

Justin James
Justin James

I just wanted to point out, refactoring is used by everyone (or should be used by everyone when needed), not just people using Extreme Programming. Not only does it help you to keep your code clean, but it also is a good way to perform an informal code review. I cannot tell you how many "compiles, but won't run right" bugs I have found while shuffling my functions around. J.Ja

Justin James
Justin James

Good point, any refactoring should be cause for a full re-run of the tests for the code, and unit tests are the best kind of testing for post-refactoring to make sure that the logic stayed the same. J.Ja

cameron.duffy
cameron.duffy

Adding dingleberries like refactoring to the anus of VS isn't going to make me more productive or write readable code given that the IDE in likely to crash, automatically rewrite code and otherwise squander any timesaving or readability improvements. We call it Visual Stupido, and that's with Intellisense on. I won't even mention VSS...

Justin James
Justin James

Stan - Thanks for the kind words, and glad you liked the article! I can't take credit for this one though, Tony Patton wrote this piece! I know that it is kind of confusing since it has my name at the top as "host". If you look at each article's header, you'll see a byline. Thanks again! J.Ja

Tony Hopkinson
Tony Hopkinson

Depends on whether performance or robustness are percieved as changes in functionality. They certainly can be, and doing them may require, further changes in percieved functionality. Refactoring for readability, to a coding standard, to allow a future enhancement, should not change existing functionality. It's hard to resist improving the functionality while you are in there, but no performance optimisation job should be described as refactoring. It's a serious Catch-22 as far as business heads are concerned. I'm going to change the code for a potential improvement to maintainenace and no user improvement can be hard to resource, except in big lumps. Business heads still don't get the idea that software changes, simply by existing. I'm going to change the code for a potential improvement to maintainenace, and this will have a currently unknown impact on user perception is quite rightly even more hard to sell. Refactoring / rewriting / re-engineering is something you have control the scope of. No coder is ever really happy with their code, and usually even less happy with someone elses, the urge to tweak an twiddle is very strong, and can get out of hand quick. Tony the tweaker

mattohare
mattohare

If I had a penny for each time I heard people talking of making applications 'without a single line of code', I think I'd be rich enough not to worry about anything. I hear this even from Microsoft 'developers' that come and visit Users Group meetings. Building applications does involve writing code. It's like saying 'With this tool, you can farm and never touch dirt.' Using the tool always seems to get a person more soiled than the work would have done in the first place. Refactoring is a great tool for coding well. You still need to watch what you're doing. When you're working, there's no way around it. Anyone that says otherwise is just trying to sell you something dodgy.

Justin James
Justin James

... is easy for me. My boss is a programmer. He often insists that something be refactored. :) J.Ja

normhaga
normhaga

Works very well with Eclipse. Works well with NetBeans. Is scary with VS 2008.

jck
jck

i have nightmares with it under Vista Business at work, and it seems that Vista and all its hard running, hard working processes in the background have led to a hard drive wearing out in my laptop in 16 months. as for refactoring, it does have to be balanced. you have to compare ROI for time spent vs benefit...plus...does the upgrade from VS2005 to VS2008 really benefit your org? as for informal code reviews...they stink. having a group sit down and look over one another's code can never be replaced...both from a syntactical standpoint...but from a functional interface as well. most people never catch all the nuances themselves of another user. I think "Extreme Programming" is just another coined phrase for companies expecting less staff to do more...i.e.- informal code reviews, self-reliance on QA at the programming level, etc. I'm dealing with that myself at the company I'm at now. I'm the R&D, design, development, test, implementation, human factors, and documentation person all in one.

mattohare
mattohare

Without the refactoring, I've used a method that seems like my barber uses. Barber Method: Cut the bangs/fringe, then cut the rest behind them to match. My Method: Make the changes in the declarations, and keep moving through the code to match it. Sometimes this goes to new levels when I have a table, a stored procedure, and a VB code method to match.

Tony Hopkinson
Tony Hopkinson

Simply to give the wider business some confidence that your improvements haven't 'broken' anything. The more your codebase is in need of refactoring, the more critical they become. One oops and you get the code left as it is, because it's safer. In their eyes at least. Always bar in mind though to get the best out of unit tests, you have to write testable code. In fact you can end up refactoring to do just that.

Tony Hopkinson
Tony Hopkinson

POS at it's smelliest. Can't say I've had that many crashes with Vs2005 and now 2008 though. Auto code generation well, that can be a productivity enhancer, definitely is if you are in need of a lot of turd.

mattohare
mattohare

When I say perform better, I mean keeping out benign bugs that may slow the application instead of crash it. Well written, easy-to-read, code is easier to proof. There are several methods that I've written, and they worked well. When I went over the whole function again, I was able to see some extra variables and extra assignments that didn't need to be there. I could also find logic challenges that might not have been easy to build on. These would not be bugs now, but would become performance issues in future.

Justin James
Justin James

There are some things which can improve performance which I put under the heading of "refactoring", like storing the end condition of a loop in a variable and checking against that value isntead of recalculating it on every loop ("iMaxValue = Array.Count - 1;" as opposed to "for (iCounter = 0; iCounter < Array.Count - 1; iCounter++)") But I tend to do that directly when writing the code now, out of habit, even though I am fairly certain than the C# compiler auto-optimizes that (the VB.Net compiler, at least the last time I compared, did *not* auto-optimize that). J.Ja J.Ja

Tony Hopkinson
Tony Hopkinson

They make really interesting noises, when you hit them with something heavy.

Tony Hopkinson
Tony Hopkinson

a tad higher up the food chain as well. Don't get me wrong I can re-factor any time I like, as long as it takes no time and there's no risk of anything changing. I bravely renamed a local variable the other day. :(

Justin James
Justin James

I've never had a problem with the refactoring tools in VS2008, but everyone has a different idea of "refactoring" too. What did you not like about it in VS2008? J.Ja

Justin James
Justin James

"i have nightmares with it under Vista Business at work, and it seems that Vista and all its hard running, hard working processes in the background have led to a hard drive wearing out in my laptop in 16 months." I had my first drive crash in this PC a few weeks ago (thank goodness for RAID 1), about 16 - 18 months after I put it together with Vista on it. But I don't think that's Vista's fault. For the last 10 years, I average 1 drive failure every 18 months or so. No idea why. I seem particularly unlucky with drive longevity. "as for refactoring, it does have to be balanced. you have to compare ROI for time spent vs benefit..." A lot of that depends on what you call "refactoring". For some, simply going through the code and turning large code blocks into separate functions is "refactoring". For others, there is more to it than that. "as for informal code reviews...they stink." I disagree completely. I cannot recall a single time in my life where looking at my code, formally or informally, did not help me. Also, I would never, ever suggest that formal code review be replaced. I just said that when going through your code to refactor, you do often end up finding a lot of little logic errors and other bugs. "I think "Extreme Programming" is just another coined phrase for companies expecting less staff to do more...i.e.- informal code reviews, self-reliance on QA at the programming level, etc." I feel the same was about "Agile" in many cases. Like someone decided that programmers were cheaper per-hour than PMs, so the "solution" was to find a way to make PMs no longer needed. 90% of the coding jobs I've had, I was like you, the whole development team rolled into one, and I loved having the control, but sometimes I felt really out of my league, ill-equipped to handle all of those roles, or otherwise in need of help that just wasn't there. J.Ja

Justin James
Justin James

Matt - That is about the process that I used to use too... it's how I got to learn the regex syntax of a text editor or too... it's just so unreliable though, it seems like you always miss something. At least with compiled languages, you find it right away, but in dynamic languages, who know when the problem will pop up? Certain types of refactoring (like renaming methods, extracting fields, etc.) are the exact kinds of repietitive, "details are the key" tasks that computers were invented to solve. :) J.Ja

Justin James
Justin James

A lot of developers I know complain that their bosses don't know how to program. Honestly, I've had bosses that didn't know how to program, and it wasn't a problem. Why? Because they knew *about* programming. As long as the boss knows what you do and why you do it, they don't need to know how you do it. :) It sounds to me like maybe the management of your group/company needs to learn a bit more about what their workers do, so that they can better handle it. J.Ja

jslarochelle
jslarochelle

The problem however is that they don't really understand the dynamic and power of unit tests. Sometimes when the schedule is tight they will say things like: "maybe we can work on the unit tests after shipping the beta version" not understanding that postponing the unit tests will very probably actually slow things down and compromise the quality of the code. There is a lot of education to be done. They also don't like refactoring. In fact they are terrified at the thought of us making any modification to the code that does not either fix a bug or add a feature. Again here, part of the problem is that they still have a lot to learn about software development (the dynamic between unit tests and refactoring being just a small part of that). Building infrared spectrometer ... piece a cake. Writing software is something else however. I also agree that poor encapsulation is a big part of the problem when trying to unit test legacy code. JS

Tony Hopkinson
Tony Hopkinson

Even my bosses agree unit testing is good. That bit about refactoring and in fact in some cases effectively rewriting, well they don't like that cost. They'd rather have the known. Generally the thing that makes wrting unit tests hard is poor encapsulation, which not co-incidentally, is one of the hardest things to put back in if you let it go too long.

jslarochelle
jslarochelle

Although I don't do "test first programming" I do test early. Doing this, I see more and more the benefits of writing unit testable code from the start. I see classes with better cohesion and less coupling. Existing unit tests act as a break for chaotic development (insertion of inapropriate dependency or responsibility). The challenge is adding unit test code to existing code base. This is more tricky because in some cases you have to refactor to get really good unit test so you get into a "chiken and egg" problem. It is still very much worth the effort. JS

jslarochelle
jslarochelle

Although I don't do "test first programming" I do test early. Doing this, I see more and more the benefits of writing unit testable code from the start. I see classes with better cohesion and less coupling. Existing unit tests act as a break for chaotic development (insertion of inapropriate dependency or responsibility). The challenge is adding unit test code to existing code base. This is more tricky because in some cases you have to refactor to get really good unit test so you get into a "chiken and egg" problem. It is still very much worth the effort. JS

Tony Hopkinson
Tony Hopkinson

bright spark came up with the idea of only having one server between two separate parts of the business separated by a few hundred miles and a leased network link. VSS or that, rock and a hard place. :(

Justin James
Justin James

VSS is indeed... nasty. I just put TFS in place, and we're very happy with it. The biggest issue was bringing in a project or two that were set up oddly to begin with (multiple solutions importing the DLLs from the "Debug" directory of other solutions, instead of the "output" or a copy of said DLLs being in the other solution). Auto code generation, yeah, it's usually lousy... but it sure beats hand-writing code based on a WSDL, for example... J.Ja

Tony Hopkinson
Tony Hopkinson

a side effect in movement of an iterator. I think I'd 'fix' that before considering leaving the unrefactored code in. If that wasn't possible then, you might see a rare thing, a comment in my code. An impolite one possibly, but definitely useful.

Justin James
Justin James

... it is *minutely* possible that advancing Number's iterator has a "side effect", so changing the code to: foreach (Int32 i in Number) { if (i == 22) { return true} } return false may not actually be 100% equivalent. Of course, it would be insanity for an iterator to have side effects, but I've seen some strange code in my time... J.Ja

Tony Hopkinson
Tony Hopkinson

instead of performance. JJ made the same point. This is a classic. bool found = false; foreach(Int32 i in Numbers) { if ( i== 22) { found = true} } return found; Refactoring opportunities abound. But this is called from a user driven event and Numbers is a big booger, you aren't going to be able to tell anyone non-technical that you haven't changed the functionality and look credible. You might wonder how such a piece of poor code got in there in the first place, I often do. :(

Tony Hopkinson
Tony Hopkinson

One you'll develop a good habit and two overall your code will be a smidgeon faster. If it made a perceptible differnce in performance as far as a user was concerned I'd be having a serious look at how often it was being called, and why. You can certainly refactor and improve an aspect of performance, however there are, if it was a perceptible saving, knock on effects. No longer needing a progress bar for instance. The flicker of it coming up and going away can be seen as a bug. It getting killed even beofre it manages to paint can be. "I clicked on the button and nothing happened, no pogress bar or anything" .... Then there's the real kiddies, such as dependancies in asynchronous messages. Don't ask me what pratt did that, but it happens. All I'm saying is be careful the expected pat on the back doesn't become a kick in the arse. To me refactoring is a process improvement not a product improvement. The latter is a byproduct of improving the process. The deliberate blurring was simply a self defeating way of getting some refactoring past the bean counters.

mattohare
mattohare

are they always listed on some endangered species list? EndangerING species, more like! *chuckle*

Justin James
Justin James

... my immediate boss is also the president & co-owner of the company. :) J.Ja

mattohare
mattohare

as much as the tools that come with it. I get the feeling you mean the same thing. There are some programming platforms that are interpreted, but the code is reviewed by an interpreter for some syntax check. Stored Procedures are an example of this. Generally, any stored plan is still interpreted. At least we developers know if we got some syntax wrong the same as if we were in a compiled C or Pascal environment.

Justin James
Justin James

Where interpreted code is dangerous (not just in a refactoring scenario, either!) is around the edge cases (especially non-deterministric ones), stuff that compiles fine. Of course, all code is like this, but interpreted/dynamic languages have always "felt" more prone to these kinds of errors to me. Or maybe that is because when I was working primarily in these languages, I was much less experienced. I use Perl and VBA a few times a year for minor utility stuff, but C# is my current mainstay and before that it was VB.Net. J.Ja

mattohare
mattohare

Even the interpreted stuff (stored procedures) have some immediate feedback if something's wrong. My compiled stuff always had facility for strong type/declaration checking. And then, my naming standards are rather rigid. With all of that, nothing's likely to slip through the cracks. Now that I'm doing some php (in notepad), things are getting a bit tougher to find. Luckily, for that I can still use my good practices learned back in the mid '80s when I was VAXinated on DEC Pascal.