C# Tutorial - Application 5 – Refactoring


Create a new console Application called App05. We are going to simplify the previous application by adding a method. The method is being added because we have some code that is very similar except for variable names. Duplicated code should be turned into a method to allow ease of maintainability.

  1. Highlight the code from the label first: through to the end of the catch statement.
  2. Right-click over the highlighted code and select Refactor.
  3. Now select Extract Method.
  4. In the dialog box that appears, choose a name for the new method such as GetNumber.


  5. The method signature needs a slight tweak for what we want. Delete the parameter.
  6. Now add a local variable in the method, so that the code looks like the following.

    Using System;
    
    class Program
    {
      static void Main(string[] args)
      {
        // Storage
        int value1 = 0;
        int value2 = 0;
        int total = 0;
    
        // Get first number
        value1 = GetNumber();
    
        // Get second number
        value2 = GetNumber();
    
        // Add them together
        total = value1 + value2;
    
        // Output the answer
        Console.WriteLine("The total is {0}", total);
      }
    
      // Get each number
      private static int GetNumber()
      {
        int i = 0;
        first:
        try
        {
          Console.Write("Enter a whole number: ");
          i = System.Convert.ToInt32(Console.ReadLine());
        }
        catch (System.ArgumentNullException)
        {
          Console.WriteLine("String is null.");
          goto first;
        }
        catch (System.FormatException)
        {
          Console.WriteLine("String does not consist of an " +
              "optional sign followed by a series of numbers.");
          goto first;
        }
        catch (System.OverflowException)
        {
          Console.WriteLine("Overflow in string to int conversion.");
          goto first;
        }
        return i;
      }
    }


<< Previous Contents Next >>

© Publicjoe, 2008