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.

6 comments:

  1. 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.

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

    ReplyDelete
  3. This doesn't work in VB does it?

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

    ReplyDelete
  5. 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

    ReplyDelete
  6. This comment has been removed by a blog administrator.

    ReplyDelete