Posted by & filed under C#.

The C# IDE includes a suite of tools that automate many common code refactoring tasks. Refactoring is a formal and mechanical process, used to modify existing code in such a way that it is improved 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 easier to maintain and extend for a long time.

Visual Studio 2005 does a great deal to automate the refactoring process. Using the Refactoring menu, related keyboard shortcuts, SmartTags, and/or context-sensitive mouse right-clicks, you can dramatically reshape your code with great ease.

The refractoring techniques include:

  • Extract Method. This allows you to define a new method based on a selection of code statements.

  • Encapsulate Field. Turns a public field into a private field encapsulated by a .NET property.

  • Extract Interface. Defines a new interface type based on a set of existing type members.

  • Reorder Parameters. Provides a way to reorder member arguments.

  • Remove Parameters. As you would expect, this refactoring removes a given argument from the current list of parameters.

  • Rename. This allows you to rename a code token (method name, field, local variable, and so on) throughout a project.

  • Promote Local Variable to Parameter. Moves a local variable to the parameter set of the defining method.

    Extraction technique is as explained as a code.

    using System;
    namespace RefactoringExamples
    { class Program
    { static void Main(string[] args)
    { Console.WriteLine(”*** Please enter your credentials ***”);
    // Get user name and password.
    string userName;
    string passWord;
    Console.Write(”Enter User Name: “);
    userName = Console.ReadLine();
    Console.Write(”Enter Password: “);
    passWord = Console.ReadLine();
    } }}

    Ideally, you could refactor the Main() method in such a way that the common logic is scraped into a new method, named (for example) GetCredentials(). By doing so, any member of the Program type who needs to obtain the user name and password could simply invoke the new method.

    The resulting extraction is:

    using System;
    namespace RefactoringExamples
    { class Program
    { static void Main(string[] args)
    { Console.WriteLine(”*** Please enter your credentials ***”);
    // Get user name and password.
    string userName;
    string passWord;
    GetCredentials(out userName, out passWord);
    }
    private static void GetCredentials(out string userName, out string passWord)
    { Console.Write(”Enter User Name: “);
    userName = Console.ReadLine();
    Console.Write(”Enter Password: “);
    passWord = Console.ReadLine();
    } }}

    From: Microsoft

Comments are closed.