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

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

Archives

RSS InfoQ Feeds

  • How Google Develops New Managers
    Alex Langshur, host of Google Partners Podcasts, has organized the podcast Google HR secrets: identifying & developing great managers, interviewing Sarah Calderon, People Development at Google, on how Google selects, trains, and develops their managers. By Abel Avram
  • Presentation: Cognitive Services, Next Step in Creating Our Robot Overlords
    Harold Pulcher discusses Cognitive Services, how to get started using them, and how to incorporate speech, image, and facial recognition into an application. By Harold Pulcher
  • Presentation: Control Flow Integrity Using Hardware Counters
    Jamie Butler and Cody Pierce discuss a new system for early detection and prevention of unknown exploits. Their system uses Performance Monitoring Unit hardware to enforce coarse-grained Control Flow Integrity (CFI). They intend to prove that their approach is effective and suitable for practical use, while staying resistant to bypass. By Jamie Butler
  • JetBrains Launches GoLand Go IDE
    JetBrains has moved its Go IDE from its early access programme to market. Now branded as GoLand, the IDE extends the IntelliJ platform making its core functionality specific to Go. This follows suit with their other language-specific tools such as PyCharm for Python and RubyMine for Ruby. By Andrew Morgan
  • Panel on the Future of AI
    An SF QCon panel on the future of AI explored some issues facing machine learning today. The areas explored: critical issues facing AI right now, how has technology changed the way people are hired, how non-leading edge companies make the best use of current technologies, what the role of humans in relation to AI is, and exciting new breakthroughs on the imm […]
  • Microsoft Updates Cosmos DB with Cassandra Support and Provides Better Availability Guarantees
    Last month at Microsoft Connect 2017, Azure Cosmos DB received several new updates, including support for using the Cassandra NoSQL database API and increased guarantees for availability. With the Cassandra NoSQL database API, customers can run operations inside Cosmos DB on a data model. The availability guarantee moves from 99.99 percent to 99.999 percent. […]
  • Article: Approximate Computing on WSO2: Explaining Approximation Algorithms in an Applied Setting
    In this article, we describe an example real world application of API monitoring which gets benefit by using approximate stream processing. We developed the application on top of WSO2 Stream Processor as Siddhi extension. Siddhi is the complex event processing library which acts as the event processing engine of WSO2 Stream Processor. By Chamod Samarajeewa
  • Rust in Visual Studio and VS Code
    Daniel Griffen has released a preview version of a Rust language service for Visual Studio. This plugin requires Visual Studio 2017 Preview, an experimental release stream for testing new VS features. By Jonathan Allen
  • Article: Key Takeaway Points and Lessons Learned from QCon San Francisco 2017
    The eleventh annual QCon San Francisco was the biggest yet, bringing together over 1,800 team leads, architects, project managers, and engineering directors. By Abel Avram
  • Article: Q&A With Eberhard Wolff On the Book “A Practical Guide to Continuous Delivery”
    Eberhard Wolff speaks with InfoQ about his work "Continuous Delivery: A Practical Guide", where we detail some of the major concepts behind successful CD adoption and the ripple-effect it can have on developer productivity and quality of service. By Dylan Raithel

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: