Refactoring Code using Visual Studio Extract Method

By | January 6, 2012

Visual Studio being an intelligent IDE does gives us a number of features that enhance the development of application as well as enhancing the way of coding continuously. One of such feature that has been added to VisualStudio IDE is refactoring. In this post we will see how easily we can use Refactoring feature of Visual Studio to get things done easily.

Visual Studio IDE ships with a new menu for refactoring code. Refactoring is actually a technique to change the software system in such a way so that the internal structure of the design changes and made more intuitive while the external behavior of the system remains same.

Lets take a look how the options works. In this post we are going to cover the Repeating code behaviour:

1. Refactoring a repeating code into a member:

Let us suppose we are going to refactor a code that looks like :

string arg1 = Console.ReadLine();
string arg2 = Console.ReadLine();

Console.WriteLine("You entered {0}", arg1);
Console.WriteLine("You entered {0}", arg2);

Now here the Console.WriteLine is repeating code. Now lets select the line and right click the repeating code and select Extract method. You can also press Ctrl + RM to invoke the Extract method. Let me select some portion of the code and use “Extract Method.. “. A dialog will appear which lets you rename the method extracted from the code.

The code will now look like :

static void Main(string[] args)
{
string arg1 = Console.ReadLine();
string arg2 = Console.ReadLine();

PrintMethod(arg1);
PrintMethod(arg2);
}

private static void PrintMethod(string arg1)
{
Console.WriteLine("You entered {0}", arg1);
}

Here the method is well extracted outside the body of the Main.

If you try with code that have external variables, you can see the Refactoring automatically detects it and produce the appropriate method stub. Refactoring does manual code analysis and is smart enough to detect the pros and cons of the refactored code and produce best alternative approach for you.

You should always use this menu to refactor your repeating code.

Tomorrow we will see how other menu in Refactor works. Stay tune.

Happy programming.

One thought on “Refactoring Code using Visual Studio Extract Method

  1. Pingback: Refactoring Code Rename Members using Visual Studio - Daily .Net Tips

Comments are closed.