DEV Community

Cover image for Simplify Your C# Code: Top 5 Refactoring Tools
Jatin Sharma for Documatic

Posted on

Simplify Your C# Code: Top 5 Refactoring Tools

When we hear refactoring what comes to mind? I am sure it would be like we just modify the previous code for some reason. That could be because it had some bugs or maybe it was the expensive approach. There could be thousands of reasons that you might want to refactor your code. That's why in this article you will learn what Code Refactoring is and how can one refactor their code. In this article, I'll also cover some of the most popular refactoring tools and techniques in C#.

Table of Contents

What is Code Refactoring?

Code Refactoring is the process of improving code without changing its behavior. It is often done to make code more readable and maintainable. Refactoring helps developers take existing code and make it cleaner and more reusable, which makes it easier to work with in the future.

Code Refactoring can be done at different levels. Following are some common refactoring techniques include:

  • Extract method: Refactor a portion of code into its method

  • Rename: Rename a variable or method to better reflect its purpose

  • Remove duplication: Remove repeated code by creating a share function or a class

There may be more properties, but ultimately the main point matters. Now let's take a look at some of the best tools for refactoring your code.

Resharper

Resharper is a popular C# refactoring tool that can improve code quality and maintainability. It offers a range of features, including code completion, code analysis, code formatting, code cleanup, and more.

Here's an example of using ReSharper to extract a method:

// Before method extraction
public void CalculateSalary(Employee employee)
{
    if (employee.HoursWorked > 40)
    {
        employee.Salary += (employee.HoursWorked - 40) * employee.HourlyRate * 1.5;
    }
}

// After method extraction
public void CalculateSalary(Employee employee)
{
    if (IsOvertime(employee))
    {
        employee.Salary += CalculateOvertimePay(employee);
    }
}

private bool IsOvertime(Employee employee)
{
    return employee.HoursWorked > 40;
}

private decimal CalculateOvertimePay(Employee employee)
{
    return (employee.HoursWorked - 40) * employee.HourlyRate * 1.5;
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the ReSharper tool was used to extract the overtime calculation into a separate CalculateOvertimePay method, making the code more readable and easier to maintain.

CodeRush

CodeRush is another C# refactoring tool that offers numerous features for improving productivity and code quality. It also includes a range of code templates and productivity tools.

Here's an example of using CodeRush to introduce a parameter:

// Before parametrization

public int Add(int value1)
{
    return value1 + 5;
}

// After parametrization

public int Add(int value1, int value2)
{
    return value1 + value2;
}

public int Add(int value1)
{
    return Add(value1, 5);
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the CodeRush tool was used to introduce a value2 parameter to the Add method and a second overload of the Add method that accepts only one argument and calls the version with two.

CodeMaid

CodeMaid is an open-source Visual Studio extension to cleanup and simplifies our C#, C++, F#, VB, PHP, PowerShell, R, JSON, XAML, XML, ASP, HTML, CSS, LESS, SCSS, JavaScript and TypeScript coding.

Here's an example of using CodeMaid to reorganize class members:

// Before reorganization

public class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }
    public decimal Salary { get; set; }
}

// After reorganization

public class Employee
{
    public int Age { get; set; }
    public string Name { get; set; }
    public decimal Salary { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the CodeMaid tool was used to reorganize the class members in alphabetical order by name.

Refactoring Essentials

This extension provides refactoring for C# and VB.NET, including code best practice analyzers to improve your projects. Development of this extension has wound down, it is kept in the marketplace to allow for continued installation.


// Before loop conversion

for (int i = 0; i < list.Count; i++)
{
    var item = list[i];
    // ...
}

// After loop conversion

foreach (var item in list)
{
    // ...
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the Refactoring Essentials was used to convert the for loop to a foreach loop, making the code more readable and easier to maintain.

NCrunch

NCrunch is a test runner that provides continuous testing for C# projects, including refactoring tools and advanced code coverage analysis.

Here's an example of using NCrunch to refactor a try-catch block:

// Before try-catch refactoring

try
{
    // ...
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

// After try-catch refactoring

try
{
    // ...
}
catch (CustomException ex) when (ex.Code == ErrorCode.InvalidInput)
{
    Console.WriteLine("Invalid Input");
}
catch (CustomException ex) when (ex.Code == ErrorCode.DuplicateItem)
{
    Console.WriteLine("Duplicate Item");
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the NCrunch tool was used to refactor the catch block by using multiple when clauses for more specific exception handling.

Wrapping up

These code refactoring tools can help you take your code to the next level by improving code quality, reducing complexity, and keeping your codebase maintainable and scalable.

If you want more articles on similar topics just let me know in the comments section. And don't forget to โค๏ธ the article. I'll see you in the next one. In the meantime you can follow me here:

Top comments (12)

Collapse
 
tracygjg profile image
Tracy Gilmore

Hi Jatin,
Excellent selection of tools. Personally, I think the most important "tool" a developer can have to perform refractory in a good collection of unit tests with at least 80% coverage. Otherwise as someone said, "Without unit tests you are not refactoring, you are just changing code." Unit tests are a developers safety net that alerts them when a change breaks the code.
Regards, Tracy

Collapse
 
j471n profile image
Jatin Sharma

You're absolutely right. Unit tests are crucial for safe refactoring, providing a safety net and ensuring expected behavior.

Collapse
 
ant_f_dev profile image
Anthony Fung

These look pretty cool - thanks for sharing.

I used to use ReSharper and can say that it definitely has a lot of tools. It's also helped me to naturally look for variables captured by closures, and multiple-enumerations.

However, it also has the downsides of adding processing time and using disk space for its data caches. This isn't a problem with newer/smaller projects. When using codebases that have been around for a while (where the project count in a solution goes into low tens), it can make loading a project quite slow. In such cases, I've found that the refactoring tools natively in Visual Studio are good enough such that I can do without ReSharper; I do miss some of its features though.

Collapse
 
j471n profile image
Jatin Sharma • Edited

Thanks,

It's all about trades if you are getting something then you have to trade something else. Well, if your system can take the load then there is nothing to worry otherwise anyone can use the vs code native refactoring as you mentioned.

Collapse
 
shawnwildermuth profile image
Shawn Wildermuth

You misspelled Resharper as Reshaper in the beginning of the article.

Collapse
 
j471n profile image
Jatin Sharma

Thanks man, fixed it. :)

Collapse
 
tracygjg profile image
Tracy Gilmore

If you are changing or extending functionality then yes unit tests may have to be revised or increased but that is not refactoring. Refactoring is a change to the implementation without changing the public interface. Good unit tests will alert the developer of changes that breaking the interface.

Collapse
 
strredwolf profile image
STrRedWolf

The tools are great, but you must take them in balance with the situation you're coding for.

Take the method extraction example. The example is already simplified as is for a simple case of overtime pay in the US (with the exception of the use of constants). One can argue that in this case, adding another level to the call stack is unjustified and only adds more work to the compiler... and if the compiler doesn't optimize it away, the resulting code is slower.

Now when would you need to perform method extraction? When the case for overtime pay isn't so simple, for instance:

  • In France, overtime pay starts at 35 hours, not 40 in the US.
  • In some transit agencies and entertainment groups, you have the concept of overtime, spread, and holiday pay.

The take-away is that these are examples, not end goals. You will need to evaluate each tool and task for your situation, which will always be in a case by case basis.

Collapse
 
eljayadobe profile image
Eljay-Adobe

I give props to NCrunch. It is amazing. It actually makes TDD-style unit testing โ€” dare I say โ€” fun. Yes, fun!

Collapse
 
o_statistics profile image
Online-statistics.org