Refactoring code using Extract Method in Visual Studio 2010

Refactoring is the process of improving your code after it has been written, by changing the internal structure of the code without affecting its functionality. Extract Method is a refactoring operation in Visual Studio 2010 that provides an easy way to create a new method from a code fragment, in an existing member.

In order to use Extract Method, you require to select a code fragment. Let us see an example:

Check this piece of code

CodeToRefactor

In the code above, the process of checking the validity of the connection string should ideally be put in a new method. This is very simple using the Extract method refactoring. Just select the code fragment and right click > Refactor > Extract Method (or Ctrl + R, Ctrl + M) as shown below:

Extract Method Refactor

In the Extract Method dialog box, enter the new method name and hit OK

Extract Method dialog

When you click OK, Visual Studio 2010 creates a new method and moves the selected
code fragment to the body of the new method, in our case AlternateConnectionString(). It also creates appropriate parameters and even returns a value, if needed, by the calling code.

The original code (where the code fragment was), is replaced with a call to the new method, with any applicable parameters that are to be passed to the new method or add a local variable to receive the return value.

The code fragment after refactoring looks like this:

Refactored Code

Note: The Extract Method Refactor is smart! For eg: if your code does not access any instance-specific data, the Extract method refactoring makes the new method static.

Similarly, you can even extract a single line of code or a portion of a code, as its own method.






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

6 comments:

Agileotter said...

The extracting is easy enough, but maybe you or I should write an article about unweaving the part you want to extract first. I have been seeing a lot of 'extract method' done badly, and we could teach how to do it better.

Suprotim Agarwal said...

I like your suggestion Tim. Would you be interested in doing a guest post here?

Anonymous said...

This doesn't work in VB does it?

Suprotim Agarwal said...

As far as I remember, VB.NET is not supported

Rory said...

VS may not support VB.net, but CodeRush Xpress does.

It provides a superior version of this and many other features for both VB.net and C#.

And the best bit.... It's FREE! :D

see http://devexpress.com/crx

Rory said...
This comment has been removed by a blog administrator.