Code refactoring is the process of restructuring existing code without changing its external behavior to improve its readability, maintainability, and performance. In C#, there are several common code refactoring techniques that can be applied:
1. Extract Method: If a block of code performs a specific task, it can be extracted into a separate method and called whenever needed. This improves code reuse and readability.
Before refactoring:
“`csharp
public void ProcessData()
{
// code here
Console.WriteLine(“Step 1”);
// more code here
Console.WriteLine(“Step 2”);
// more code here
}
“`
After refactoring:
“`csharp
public void ProcessData()
{
Step1();
Step2();
}
private void Step1()
{
Console.WriteLine(“Step 1”);
}
private void Step2()
{
Console.WriteLine(“Step 2”);
}
“`
2. Rename Variables and Methods: Providing meaningful names to variables and methods enhances code readability and understanding.
Before refactoring:
“`csharp
public void Calc(int a, int b)
{
int c = a + b;
Console.WriteLine(c);
}
“`
After refactoring:
“`csharp
public void CalculateSum(int num1, int num2)
{
int sum = num1 + num2;
Console.WriteLine(sum);
}
“`
3. Remove Duplicated Code: If the same code is repeated multiple times, it should be replaced with a single reusable method or property.
Before refactoring:
“`csharp
public void PrintRectangleArea(int length, int breadth)
{
int area = length * breadth;
Console.WriteLine(area);
}
public void PrintSquareArea(int side)
{
int area = side * side;
Console.WriteLine(area);
}
“`
After refactoring:
“`csharp
public void PrintArea(int side)
{
int area = side * side;
Console.WriteLine(area);
}
public void PrintRectangleArea(int length, int breadth)
{
int area = length * breadth;
Console.WriteLine(area);
}
“`
4. Replace Magic Numbers: Replace hard-coded values with named constants or variables to improve code readability and maintainability.
Before refactoring:
“`csharp
public void CalculateCircleArea(double radius)
{
double area = 3.14 * radius * radius;
Console.WriteLine(area);
}
“`
After refactoring:
“`csharp
private const double Pi = 3.14;
public void CalculateCircleArea(double radius)
{
double area = Pi * radius * radius;
Console.WriteLine(area);
}
“`
These are just a few examples of code refactoring techniques in C#. The goal is to make the code more readable, maintainable, and efficient.