Friday, August 27, 2010

Visual Studio Tip of the day - Refactoring - Extracting method

You notice that you have a chuck of code which could easily be transitioned to a new function. How tdo you do that?

Again, Visual Studio Refactoring menu comes to the rescue.

Suppose you have the following code in your function

public void Myfunc()

{

   Console.WriteLine("a");

   Console.WriteLine("b");

   Console.WriteLine("c");

   // Do some processing here.

   Console.WriteLine("a");

   Console.WriteLine("b");

   Console.WriteLine("c");

}

 

We realize that code containing Console.Writeline is replicated. Select one set of the Console.Writeline instructions and right click > Refactor > Extract Method...

Type the name of the new function you want to create containing the selected lines and Click OK.

A new method containing the selected lines is created. So your code will look like

public void Myfunc()

{

   NewMethod();

   // Do some processing here.

   Console.WriteLine("a");

   Console.WriteLine("b");

   Console.WriteLine("c");

}

private static void NewMethod()

{

   Console.WriteLine("a");

   Console.WriteLine("b");

   Console.WriteLine("c");

}

 

Keyboard shortcut: Ctrl R + Ctrl M

Cavaet: You will have to delete the second set manually as currently VS editor is not smart enough to replace all the occurances of the selected lines. Maybe in the next version we can get that feature.

No comments: