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.

devx-admin

devx-admin

Share the Post:
Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining