DEV Community

mohamed Tayel
mohamed Tayel

Posted on • Edited on

Mastering C# Fundamentals: Refactoring Methods into Separate Files

Refactoring Methods in C#: A Step-by-Step Guide to Cleaner Code

As developers, we often start small by placing all code in the Program.cs file. This approach works fine for simple projects but becomes unmanageable as the application grows. To maintain a clean, scalable, and maintainable codebase, we need to refactor the code—reorganizing it into separate files and classes. This practice is fundamental to writing professional, maintainable code.


What is Refactoring?

Refactoring is the process of restructuring existing code without changing its functionality. It improves code readability, maintainability, and scalability by separating logic into well-defined components. For example, moving methods to separate classes or files ensures better organization and reusability.


Why Refactor Code?

Refactoring offers several advantages:

  1. Improved Readability: Separate files and classes make it easier to find and understand code.
  2. Enhanced Reusability: Centralized methods in utility classes can be reused across the application.
  3. Simplified Maintenance: With clear separation of concerns, updates become easier and safer.

Refactoring in Action: Moving Methods to a Separate File

In this guide, we’ll refactor the CalculateTotalPrice method from Program.cs into a new class in a separate file.


Step 1: Create a New Class

  1. In Visual Studio, right-click on the project in Solution Explorer.
  2. Select Add -> New Item.
  3. Choose Class, name it Utilities.cs, and click Add.

This creates a new file named Utilities.cs with a class structure like this:

namespace YourNamespace
{
    public class Utilities
    {
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Move the Method to the New Class

  1. Open Program.cs and locate the CalculateTotalPrice method.
  2. Cut the method and paste it into the Utilities class inside Utilities.cs.

Updated Utilities.cs:

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: Update the Access Modifier

The method is now in a different class, so it must be public to make it accessible outside Utilities. This ensures it can be called from other files:

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

Step 4: Update the Program.cs File

Replace the old method call in Program.cs to reference the Utilities class:

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
  • The using YourNamespace; directive ensures that Program.cs can access Utilities.

Step 5: Fix Namespaces (if necessary)

If you encounter an error like "Utilities cannot be found," add the appropriate using directive:

  1. Hover over Utilities and accept the Visual Studio suggestion to add the using directive.
  2. Ensure the namespace of Utilities.cs matches your project structure.

Step 6: Test Your Refactored Code

Run the application to ensure it functions as expected. The output should remain the same, but the project structure is now cleaner and more maintainable.


Advantages of Refactoring into Separate Files

  1. Separation of Concerns: Organize related functionality into specific classes.
  2. Code Reusability: Methods in utility classes can be reused across the project.
  3. Scalability: As the application grows, you can add more classes and files, keeping the codebase organized.
  4. Improved Collaboration: With separate files, multiple developers can work on different components simultaneously.

Best Practices for Refactoring

  1. Group Related Methods: Keep methods with similar functionality in the same class.
  2. Use Meaningful Names: Name classes and methods descriptively to clarify their purpose.
  3. Maintain Single Responsibility: Each class should focus on one task or responsibility.
  4. Keep It Small: Avoid large, monolithic classes or methods.

Conclusion

Refactoring is a critical skill for managing growing codebases. By moving methods to separate files and organizing them into well-defined classes, you create a scalable and maintainable project structure. This practice not only improves readability and maintainability but also lays the foundation for future development.


Key Takeaways:

  • Refactoring reorganizes code for better clarity and scalability without changing functionality.
  • Moving methods into separate files promotes separation of concerns and reusability.
  • Use access modifiers (public) to control method accessibility.
  • Import appropriate namespaces when calling methods from different files.

By following these steps, you’ve successfully refactored your code to be cleaner and more maintainable. With every refactor, you’re one step closer to mastering professional development practices in C#.

Top comments (0)