BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Refactoring
VS 2005+

Visual Studio Extract Method Command

When a method grows too large to be easily manageable, or when a section of a method will be duplicated elsewhere in your code, you may consider extracting part of the code into its own method. Visual Studio can automate this refactoring process.

Extract Method Command

Visual Studio includes several refactoring tools that allow existing code to be improved through restructuring. One of these is the Extract Method command. This useful command allows you to specify a number of lines of code that exist within a class member and instruct Visual Studio to extract the code into its own method, replacing the original lines with a call to the new member.

The command examines the code being extracted to determine whether one or more return values will be required and to identify any variables that should become parameters of the new method. Each of these items is automatically implemented.

Methods should be created from extracted code when existing class members become too large or where the same code is being repeated in multiple areas, decreasing maintainability. When used correctly, the process simplifies the code and improves its readability and maintainability. It also encourages reuse, lowers duplication and is helpful for creating self-documenting code.

Extracting a Simple Method

The simplest form of method extraction moves a section of reusable code to its own method. The new method requires no parameters and does not return a value. The method will be private and will be either a static or instance member to match the member that the code was extracted from.

To demonstrate, we need some code to refactor. In the sample code below, a single method is used to request the details of the server, instance and database for a SQL Server database. These details are combined into a connection string before a method is called that opens a connection the database. A final call reads some key data from the database. These two methods, named "OpenDatabaseConnection" and "ReadKeyData" are omitted for clarity. The method includes code that could be reused or refactored to make the code clearer.

public void ReadUserSelectedDatabase()
{
    Console.WriteLine("The requested feature requires a database.");
    Console.WriteLine("You must provide the details of a SQL Server database.");
    Console.WriteLine("Server and database are required, instance is optional.");
    Console.WriteLine();

    Console.WriteLine("Server?");
    string server = Console.ReadLine();
    server = server.Trim();

    Console.WriteLine("Instance?");
    string instance = Console.ReadLine();
    instance = instance.Trim();

    Console.WriteLine("Database?");
    string database = Console.ReadLine();
    database = database.Trim();

    string serverAndInstance;
    if (instance.Length == 0)
        serverAndInstance = server;
    else
        serverAndInstance = string.Format(@"{0}\{1}", server, instance);

    string connectionString = string.Format(
        "Data Source={0};Initial Catalog={1};Integrated Security=SSPI;",
        serverAndInstance, database);

    OpenDatabaseConnection(connectionString);
    ReadKeyData();
}

The first part of the method uses four statements to output a message to the user, indicating that some connection information is required. This message could be reused so we should extract it to its own method. To do so, select the first four lines of code from the method, then right-click the selection to display a context-sensitive menu. From this menu, select "Refactor", then "Extract Method..." to display the Extract Method dialog box.

Visual Studio Extract Method Command

The Extract Method dialog box allows you to specify the name for the new method. Enter "ShowDatabaseRequiredMessage" for the method name. The signature of the new method will be displayed in the preview area. Click OK to complete the process.

Visual Studio Extract Method Dialog Box

After the extraction, the selected code will be moved to a new method and replaced with a call to that method.

public void ReadUserSelectedDatabase()
{
    ShowDatabaseRequiredMessage();

    Console.WriteLine("Server?");
    string server = Console.ReadLine();
    server = server.Trim();

    Console.WriteLine("Instance?");
    string instance = Console.ReadLine();
    instance = instance.Trim();

    Console.WriteLine("Database?");
    string database = Console.ReadLine();
    database = database.Trim();

    string serverAndInstance;
    if (instance.Length == 0)
        serverAndInstance = server;
    else
        serverAndInstance = string.Format(@"{0}\{1}", server, instance);

    string connectionString = string.Format(
        "Data Source={0};Initial Catalog={1};Integrated Security=SSPI;",
        serverAndInstance, database);

    OpenDatabaseConnection(connectionString);
    ReadKeyData();
}

private static void ShowDatabaseRequiredMessage()
{
    Console.WriteLine("The requested feature requires a database.");
    Console.WriteLine("You must provide the details of a SQL Server database.");
    Console.WriteLine("Server and database are required, instance is optional.");
    Console.WriteLine();
}
1 January 2009