DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Mastering C# Fundamentals: Refactoring Methods into Separate Files

So far, we’ve placed all our code inside the Program.cs file, which works for small applications. However, as our applications grow in complexity, it becomes more difficult to manage everything in a single file. To maintain clean and maintainable code, it’s best to separate logic into different files. This process of reorganizing code is called refactoring, and it’s essential for scaling your applications effectively.

In this article, we’ll walk through how to refactor an existing method by moving it into a separate file, which will contain a new class. The goal is to reorganize the code without changing the application’s functionality.

Why Refactor Your Code?

When you start developing applications, it’s common to write everything in the Program.cs file. But as your codebase grows, placing all logic in one file becomes inefficient and hard to maintain. Refactoring helps you:

  • Improve readability: Keeping related methods together in separate files makes it easier to find and understand the code.
  • Enhance reusability: By moving methods into separate classes, you can reuse them across different parts of your application.
  • Simplify maintenance: With clear separation of concerns, maintaining and updating code becomes easier.

Refactoring the Code: Moving Methods to a Separate File

Let’s start by refactoring a simple method we wrote earlier. In this example, we’ll move the CalculateTotalPrice method from the Program.cs file to a new file.

Step 1: Create a New Class
  1. In Visual Studio, right-click on your project in the Solution Explorer and select Add -> New Item.
  2. Select Class, name it Utilities.cs, and click Add.

This creates a new file called Utilities.cs containing a class named Utilities. The class looks like this:

namespace YourNamespace
{
    public class Utilities
    {
    }
}
Enter fullscreen mode Exit fullscreen mode
Step 2: Move the Method to the New Class

Now, we’ll move the method from Program.cs to the new Utilities class.

  1. Open your Program.cs file and find the CalculateTotalPrice method.
  2. Cut the entire method from Program.cs.
  3. Open Utilities.cs and paste the method inside the Utilities class, like this:
namespace YourNamespace
{
    public class Utilities
    {
        public static decimal CalculateTotalPrice(decimal pricePerItem, int quantity)
        {
            decimal totalPrice = pricePerItem * quantity;

            if (quantity > 5)
            {
                totalPrice *= 0.9m; // Apply 10% discount
            }

            return totalPrice;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
Step 3: Make the Method Accessible

Since the method is now inside a different class, we need to make sure it’s accessible from outside the Utilities class. To do this, we declare the method as public:

public static decimal CalculateTotalPrice(decimal pricePerItem, int quantity)
Enter fullscreen mode Exit fullscreen mode

The public keyword allows other classes to access this method. We also keep the static keyword because we want to be able to call this method without creating an instance of the Utilities class.

Step 4: Update the Program.cs File

Now that the method has been moved to the Utilities class, we need to update the Program.cs file to use this method from its new location.

In Program.cs, replace the old method call with this:

decimal itemPrice = 20.50m;  // Price of each item
int numberOfItems = 7;       // Quantity

decimal totalPrice = Utilities.CalculateTotalPrice(itemPrice, numberOfItems);
Console.WriteLine($"The total price is: {totalPrice}");
Enter fullscreen mode Exit fullscreen mode

In this line, we call the CalculateTotalPrice method from the Utilities class by using the class name followed by a dot (.) and the method name.

Step 5: Fix Namespaces (if needed)

If Visual Studio shows an error like "Utilities cannot be found," you may need to import the correct namespace. To do this:

  1. Hover over Utilities.
  2. Visual Studio will suggest adding a using directive. Accept the suggestion to automatically add the namespace at the top of the file.

Your Program.cs file should now look like this:

using YourNamespace;

class Program
{
    static void Main(string[] args)
    {
        decimal itemPrice = 20.50m;  // Price of each item
        int numberOfItems = 7;       // Quantity

        decimal totalPrice = Utilities.CalculateTotalPrice(itemPrice, numberOfItems);
        Console.WriteLine($"The total price is: {totalPrice}");
    }
}
Enter fullscreen mode Exit fullscreen mode
Step 6: Run the Application

Now, run your application. The functionality remains the same, but the CalculateTotalPrice method has been moved to a new file, making your project structure cleaner and easier to manage.

Benefits of Refactoring into Separate Files

  1. Separation of Concerns: By moving methods into specific classes, each class focuses on a single responsibility, leading to better-organized code.
  2. Reusability: Methods stored in separate files or utility classes can be reused in different parts of the application without duplication.
  3. Scalability: As your project grows, you can continue organizing related methods into different files, improving the overall structure.

Conclusion

Refactoring is an essential skill for any developer working on growing codebases. Moving methods into separate files helps make your code more maintainable, readable, and reusable. While the functionality of your application stays the same, refactoring keeps your project clean and organized.

Key Takeaways:

  • Refactoring helps improve the structure of your code without altering its behavior.
  • Moving methods to separate files makes your code easier to maintain and scale.
  • Use the public keyword to make methods accessible from outside their class.
  • Import the necessary namespaces when calling methods from different files.

With this simple refactoring, you’ve taken a step toward writing more maintainable and professional C# code. Keep refactoring as your application grows to ensure your code remains clean and easy to manage.

Top comments (0)