Refactoring a 3000‑Line C# Factory Class into a Concise 15‑Line Implementation

The article recounts how the author transformed a massive, repetitive three‑tier factory class in a C# data‑center management system into a clean, reflection‑based solution of just a few lines, while sharing practical refactoring lessons, pitfalls of code generators, and advice on unit‑testing and architecture design.

Architecture Digest
Architecture Digest
Architecture Digest
Refactoring a 3000‑Line C# Factory Class into a Concise 15‑Line Implementation

The author, a recent graduate working on a data‑center monitoring system built with ASP.NET, encountered a sprawling three‑tier factory class that required manual updates for every new database table, leading to duplicated, hard‑to‑maintain code.

By analysing the pattern of the className generation and the returned type, the author discovered that reflection and generics could replace the repetitive boilerplate. The refactored factory now creates instances dynamically, reducing the original dozens of screens of code to just a handful of lines.

While the reduction in line count impressed the author, he also reflected on the risks of using code‑generation tools: they hide complexity, encourage shallow understanding of three‑tier architecture, and often produce fragile code.

He warns against reinventing the wheel, illustrating with a manual implementation of String.Split() that duplicates existing framework functionality, and stresses the importance of consulting language documentation and existing libraries before writing custom code.

To avoid excessive reliance on code generators, the author suggests defining your own templates or using tools like CodeSmith, and demonstrates a more maintainable approach using reflection to load task‑handler bundles:

private void RegisterTaskHandlerBundles()
{
    var bundles = xxx.BLL.Caches.ServiceBundleCache.Instance.GetBundles("TaskHandlerBundle");
    if (bundles != null && bundles.Count > 0)
    {
        var asmCache = new Dictionary<string, Assembly>();
        foreach (var bundle in bundles)
        {
            try
            {
                if (!asmCache.ContainsKey(bundle.Category))
                    asmCache.Add(bundle.Category, Assembly.Load(bundle.AssemblyName));
                var handler = (ITaskHandler)asmCache[bundle.Category].CreateInstance(
                    bundle.ClassName, false, BindingFlags.Default, null,
                    new object[] { this, bundle }, null, null);
                _taskHandlerBundles.Add(bundle, handler);
            }
            catch (Exception e)
            {
                NLogHelper.Instance.Error("加载bundle[Name:{0},Assembly:{1}:Class:{2}]异常:{3}",
                    bundle.Name, bundle.AssemblyName, bundle.ClassName, e.Message);
            }
        }
    }
}

With this registration in place, the MainEngine no longer needs to be edited for each new feature; new functionality is added by implementing ITaskHandler and inserting a record into a configuration table, achieving a clean separation between framework and business logic.

class MainEngine : IEngine
{
    private NewFuncClass newCls = new NewFuncClass();
    public MainEngine(ConfigSettings config)
    {
        RegisterTaskHandlerBundles();
    }
    public void Start()
    {
        _taskHandlerBundles.Start();
    }
    public void Stop()
    {
        _taskHandlerBundles.Stop();
    }
}

The article also covers other practical tips: reducing dependence on code generators, preferring built‑in .NET utilities like Timer and ThreadPool over custom threading code, and using unit tests to drive refactoring (a "Test‑Driven Refactoring" approach).

Overall, the piece emphasizes that thoughtful refactoring—grounded in language features, design patterns, and automated testing—yields more maintainable, extensible, and robust backend systems.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

code-generationc++unit testingrefactoring
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.