Technology Corner

Home » DotNet » Refactoring of C# Code

Refactoring of C# Code

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 80 other followers

Twitter updates

Archives

RSS InfoQ Feeds

  • Article: Q&A on the Book "Humans vs Computers"
    Author Gojko Adzic has released a book, Humans vs Computers in which he tells stories about the impact of inflexible automation, edge cases and software bugs on the lives of real people. He explains the common mistakes built into the systems and provides advice on how to prevent these mistakes from being built into our systems in the first place. By Shane Ha […]
  • Q&A with Michael Coté on Devops Adoption and his Talk at DevOpsDays NZ
    Raf Gemmail talks to Pivotal’s Michael Coté about obstacles to DevOps adoption and his forthcoming talk at DevOpsDays NZ 2017 By Rafiq Gemmail
  • TensorFlow Serving 1.0 Release Detailed at Google I/O
    Google's Noah Fiedel details new programming model for TensorFlow Serving in a stable 1.0 release. Subject matter addresses common challenges with portability, servablility , and reproducibility improvements. By Dylan Raithel
  • First NetBeans Code Drop Lands at Apache
    Oracle has released the first of three NetBeans code drops to the Apache Incubator. By Matt Raible
  • Article: The Top 10 Adages in Continuous Deployment
    On the basis of discussions at the Continuous Deployment Summit, researchers derived 10 adages about continuous-deployment practices. These adages represent a working set of approaches and beliefs that guide current practice and establish a tangible target for empirical validation. By Chris Parnin
  • Podcast: Joshua Kerievsky and Heidi Helfand on High Performance via Psychological Safety
    In this podcast Shane Hastie, Lead Editor for Culture & Methods, spoke to Joshua Kerievsky, CEO of Industrial Logic, and Heidi Helfand, Director of Engineering Excellence at Procore Technologies and author of the book Dynamic Reteaming, about their talk High Performance via Psychological Safety. By Joshua Kerievsky
  • Spotify and Google Release Forseti GCP Security Tools
    Google has opened up Forseti Security, a set open source tools for GCP security, to all GCP users. The project is the result of a collaborative effort from both Spotify and Google, combining what was originally separate work together into a single toolkit. It aims to automate security processes for developers in order for them to develop more freely. By Andr […]
  • Article: Q&A on the Book SAFe Distilled
    The book SAFe Distilled breaks down the complexity of the framework into easily understood explanations and actionable guidance. It’s a resource for acquiring a deep understanding of the Scaled Agile Framework, and how to implement it successfully. By Ben Linders
  • String Interpolation in Entity Framework Raises Concerns
    One of the new features in Entity Framework Core 2 is the ability to automatically convert interpolated strings into parameterized SQL. Though designed to avoid problems with poorly written SQL, it is feared that it may actually lead to more SQL injection attacks. By Jonathan Allen
  • Podcast: Twitter's Yao Yue on Latency, Performance Monitoring, & Caching at Scale
    Yao Yue spent the majority of her career working on caching systems at Twitter. She created a performance team that deals with edge performance outliers often exposed by the enormous scale of Twitter. In this podcast, she discusses standing up the performance team, thoughts on instrumenting applications, and interesting performance issues (and strategies for […]

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

Blogs I Follow

%d bloggers like this: