DotNet

Refactoring of C# Code


What is Refactoring?

Refactoring of code helps to restructure the code to enhance performance, scalability, reusability and code readability. There could be chances that refactoring can result in breaking of application flow when you do refactoring of big chunks of code. It is better to do refactoring of small chunks of code on regular basis.

Refactoring can includes improvements like: adhere to coding guidelines, OO principles, increase type safety, improving performance, increasing code readability and maintainability. Refactoring can be done manually and automated.

Tools to Help in Refactoring

  • VSTS
  • Re Sharper
  • Code Rush

Following are some of common refactoring operations which we do for refactoring code:

  • Extract method.
  • Extract Interface.
  • Segregate code in layers (logical or physical).
  • Convert looping (foreach) in LINQ expressions.
  • Re-Ordering of Parameters.
  • Encapsulate Field.
  • Rename method, class.
  • Put independent code which is independent of any object into static method.
  • Use of Extension methods.
  • Adhere to coding guidelines (naming, design, behavioral etc).

Extract Method

It is an easy way to extract method out of code fragment. This is useful when any block has many lines of code which can leads to maintainability problem. In this case it is advised to segregate lines of code in methods which gives better clarity of code, reusability of code,

Benefits

  • Encourage best coding practices
  • Encourage reusability of methods
  • Encourage finer grained methods to simplify overriding
  • Minimize code duplicity.
  • Unit testing can be more effective.

Code

Following is code which calculate area of rectangle:

public void Method1()
        {

            double length = 3.4d;

            double width = 4.5d;

            double a = length * width;

            Console.WriteLine("Area :{0}", a);

        }

public void Method2()
        {

            double length = 6.7d;

            double width = 42.3d;

            double a = length * width;

            Console.WriteLine("Area :{0}", a);

        }

In above code, same code has used (calculation of area) in Method2. This situation demands in refactoring of code by extracting method which will reduce duplicity of code. You can do refactored above code like below:

public void Method1()
        {

            double length = 3.4d;

            double width = 4.5d;

            CalculateAreaAndPrint(length, width);

        }

        private static void CalculateAreaAndPrint(double length, double width)
        {
            double a = length * width;

            Console.WriteLine("Area :{0}", a);
        }

        public void Method2()
        {

            double length = 6.7d;

            double width = 42.3d;

            double a = length * width;

            CalculateAreaAndPrint(length, width);
        }

You can refactored above code manually but VSTS also has commands which can easily extract method effectively.

  • Select code you want to refactor, right click and select refactor menu and then Extract Method.
  • Dialog will open to ask to for method name.

image

image

It will refactor code by extracting method.

Extract Interface

VSTS provides operation to extract interface from concrete class.

public class CandidateForInterface
    {
        public void DoSomething(int a, int b)
        {
            //do something
        }
        public void ExtractMe(double d)
        {
            //do something
        }

    }

After refactoring

 interface ICandidateForInterface
    {
        void DoSomething(int a, int b);
        void ExtractMe(double d);
    }
public class CandidateForInterface:ICandidateForInterface
    {
	....
    }

image

ForEach Loop Refactoring

Adding item from one collection to another:

Sample Code

Before Refactoring

List coll1 = new List {28,31,43,59,89,2,43,20,56};

            List coll2 = new List();

            //conventional approach
            foreach (int i in coll1)
                coll2.Add(i * 5);

After Refactoring

           coll2 = coll1.Select(i => i * 5).ToList();

Sample Code

public class Employee
        {
            public string Name { get; set; }
        }
        public class ModifiedEmployee
        {
            public string ModifiedName { get; set; }
        }
static void Main(string[] args)
        {
 	    //Transformation of one entity to another
            List list = new List ();
            Employee obj=new Employee{Name="Neeraj"};
            list.Add(obj);
            obj = new Employee{Name ="Rajeev"};
            list.Add(obj);

            // Before Refactoring
            List ModifiedList = new List();
	}

After Refactoring

  ModifiedList.AddRange(list.Select(x=> new ModifiedEmployee{ModifiedName="Mr"+x.Name}));

Reordering of Parameters

While writing code sometimes you would need to reorder parameters of methods to make it consistent across project. VSTS provide command to reorder parameters of method and also rearranged parameters where method is calling.

	public int ReturnDays(DateTime endDate, DateTime fromDate)
            {
                return endDate.Subtract(fromDate).Days;
            }

ReturnDays method has two parameters endDate and fromDate. To increase readability of code, ordering of parameters could be fromDate and endDate. To reorder parameters :

  1. Place cursor on method “ReturnDays”.
  2. Do right click, select Refactor or On the Refactor menu.
  3. Click Reorder Parameters. A Dialog box will appear.
  4. Move fromDate to up or endDate to down.
  5. Click.

image

Preview changes

image

After Refactoring Code will like this:

public int ReturnDays(DateTime fromDate, DateTime endDate)
            {
                return endDate.Subtract(fromDate).Days;
            }

Encapsulate Field

Sometimes we need to create properties from existing field. When a field is public, other objects have direct access to that field and can modify it, undetected by the object that owns that field. By using properties to encapsulate that field, you can disallow direct access to fields.

public class Employee
    {
        public string Name { get; set; }

        public string EmployeeId;
}

Above class has field EmployeeId which is public. We need to convert it into property.

  1. Place cursor on method “ReturnDays”.
  2. Do right click, select Refactor or On the Refactor menu.
  3. Click Encapsulate Field. A Dialog box will appear.
  4. Put property name if you want to give custom name.
  5. Click OK.

image

Convert into Static Method

Extract method command extract code and put into static method if selected code is not dependent on any class. For instance we are doing mathematical operation, it will extract into static method.

 int a=5,b=5;
 int d = a + b/10;

To refactor int d = a + b/10

  1. Select source code to refactor.
  2. Do right click, select Refactor or On the Refactor menu.
  3. Click Extract method. A Dialog box will appear.
  4. Give method name if you want to give custom name.
  5. Click OK.

image

After refactoring:

private static void Calculate(int a, int b){    int d = a + b / 10;}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s