devxlogo

Code Refactoring in VS.NET 2005

Code Refactoring in VS.NET 2005

evelopment is often a messy process. Often, you need to organize your code to make it more readable, or restructure it to improve readability. Manually polishing code is both cumbersome and error prone. Fortunately,VS.NET 2005’s Refactoring Tool is an awesome new feature that lets you modify your code without affecting its functionality?in other words, it helps you organize your C# code without changing the runtime outcome. This article shows you how to use the Refactoring Tool in Visual Studio.NET 2005 to refactor your C# code with ease.

According to MSDN:

“Refactoring is a formal and mechanical process, used to modify existing code in such a way that it does indeed become ‘better’ while preserving the program’s intended functionality. In addition to improving a program’s overall design, the refactoring process tends to yield code which is far easier to maintain and extend in the long run.”

Editor’s Note: Although it doesn’t ship with the product, Microsoft supplies a free add-in for refactoring VB.NET code

The Refactor Menu
In Visual Studio.NET 2005, you can invoke refactoring either from the Visual Studio menu bar or from the context menu (see Figure 1).

?
Figure 1. The Refactor Menu: The figure shows the Refactor menu options.

The Refactor menu contains the following options:

  • Rename
  • Extract Method
  • Encapsulate Field
  • Extract Interface
  • Promote Local Variable to Parameter
  • Remove Parameters
  • Reorder Parameters

The following sections discuss how you can use each of these options of the Refactor menu.

Rename
The rename option lets you rename a namespace, type, field, variable, method, or method parameter seamlessly.

When you choose this option, you’ll see the Rename dialog shown in Figure 2.

?
Figure 2. The Rename Dialog: When you select an item to rename, VS displays a dialog that lets you enter a new name, and (optionally) preview changes before applying them.
?
Figure 3. Preview Changes Dialog: You can get a good sense of how the change will affect the existing code by previewing the changes before applying them.

Figure 3 shows an example of the preview dialog that pops up after you click on the OK button in the Rename dialog in Figure 2.

Here, you can specify the new name for the token, preview changes, and even control the location where the changes would take effect.

Extract Method
Sometimes you realize that a method’s code has become lengthy, making it a nightmare to read and maintain. The answer is usually to decompose the lengthy method into shorter sub-methods?which is where the “Extract Method” option fits in. You can use this option to extract a sub-method from another method, converting a selected section of code from within a long method into a new and shorter private method. The Extract Method replaces the selected code in the original method with a call to the newly created private method containing the selected code from the original method.

?
Figure 4. Extract Method Dialog: This dialog gives you the option to assign a specific name when extracting a sub-method.

When you invoke the “Extract Method” option from the Refactor menu, you’ll see the Extract Method dialog shown in Figure 4. To complete the operation, enter a name for the new method and click on the OK button.

For example, assume that you had a lengthy method containing the following code.

   public int Add(int i,int j)   {      ...      int k = 0;      k = i + j;      return k;   }

You want to extract the three lines between the ellipses into a separate method. Select the three lines, and select the Extract Method option from the Refactor menu. In this example, I simply accepted the default name ExtractedMethod, but normally you’d provide a more explicit name. Note that VS updates the method definition in the original method to reflect the call to the newly extracted private method.

   public int Add(int i,int j)   {      ...       return ExtractedMethod(i, j);   }      private static int ExtractedMethod(int i, int j)   {      int k = 0;      k = i + j;      return k;   }

Encapsulate Field
Encapsulation is an object-oriented programming technique that isolates class members (fields) from the external world by encapsulating them within a common unit. The Refactor menu helps in this by offering the “Encapsulate Field” option, which encapsulates access to a class field by creating property accessors. The option simply generates a property wrapper around a specified class member.

You can set the property visibility, specify the property name, and even choose whether to update references to the class member from outside the class, inside the class, or both. As usual, you can preview your changes.

Extract Interface

?
Figure 5. Extract Interface Dialog: The dialog lets you provide an interface name and choose the members from which to extract the interface.

Applications often have two or more classes that have identical structure but differing implementations. In such cases, it’s often desirable to provide a common interface. You can use the Refactor menu’s “Extract Interface” option to create a new file that contains the specified interface. The option also alters the class declaration to indicate that the class implements the specified interface. When you choose this option from the Refactor menu, the window in Figure 5 pops up.

Specify the name of the interface, preview the changes, and click OK to allow the changes to take effect. As an example, consider the class shown below:

   public partial class MainForm : Form   {         //Some code      public int Add(int i,int j)      {         int k = 0;         k = i + j;         return k;      }   }

Extracting an interface for this class creates interface and updates the class definition accordingly; in other words, the process implements the extracted interface shown below:

   using System;      namespace Test   {       interface IMainForm       {           int Add(int i, int j);       }   }

Promote Local Variable to Parameter
This option lets you promote a local variable in a method to a parameter. Note that the variable should be initialized for this option to work. After the promotion, VS updates all calls to this method reflect this change.

Consider the following method:

   public int Add(int i,int j)   {      int k = 0;      k = i + j;      return k;   }

For example, suppose you promote the local variable k in the preceding code to a method parameter using the “Promote…” option. Here’s the result. Note that the method declaration changes, adding the new parameter k:

   public int Add(int i, int j, int k)   {      k = i + j;      return k;   }

Remove Parameters
You use this option to remove one or more parameters from a method and update all the calls to the method accordingly. Figure 6 shows the Remove Parameters dialog.

?
Figure 6. The Remove Parameters Dialog: Select the parameter(s) you want to remove, and then click OK.
?
Figure 7. Remove Parameter Preview: The preview lets you see the code result of removing parameters before VS applies the changes.

Select the parameter(s) that you would like to remove and then click on the OK button. A preview window (see Figure 7) pops up showing you the outcome. At this point you can still cancel the operation if you don’t like the result.

Reorder Parameters
A simpler, but welcome operation lets you reorder the parameters in a method. This also updates any calls to this method accordingly. The dialog lists the parameters. You can move parameters around in the list by selecting them, and then clicking an arrow key (see Figure 8).

?
Figure 8. Reorder Parameters: In this dialog, you move the parameters in the list until they’re in the preferred order, and then click OK.
?
Figure 9. Reorder Parameters Preview: After switching the order of the two parameters “i” and “j,” the preview shows you the result in code. You can still cancel the operation at this point.

Change the order of the parameters as per your requirements and click on the OK button. You’ll see the preview window in Figure 9.

As you’ve seen, Visual Studio’s code refactoring features let you improve the design of your existing code, facilitating its readability and simplifying its structure, all without changing its functionality.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist