Search code examples
c#genericsstatic-classes

refactoring static classes with duplicate code c#


My codebase has several different static classes (Ex: FooIO, BarIO) that have identical methods in them. The only difference in functionality between these methods is a config object (Ex: Foo, Bar) and a file name.

I pulled the actual implementation of the methods into a generic class called BaseIO.

In each IO class I have a static constructor that creates an instance of BaseIO with the proper class and fileName:

static FooIO()
    {
        configIO = new BaseIO<Foo>("Foo.xml");
    }

and for all the methods I call that instance:

public static void Save(Foo config)
    {
        configIO.Save(config);
    }

However, there's still quite a bit of duplicate code between IO classes, since everything besides the constructor is identical.

Is there anyway to further remove duplicate code from these classes without breaking existing dependencies?


Solution

  • Using statics to share data is a classical mistake. Unless it is a constant or at least readonly (runtime constant), you should resist the urge. It is one of htose things that works 95% of the times and is super easy to do, so when it stops working you have comitted to it.

    Just make a normal class that needs instantiation. Then assign a instance to a static field:

    static GenericIO<Foo> FooIO = new GenericIO<Foo>();
    

    This simple change will allow you unlimited sets of those settings. And you can also change out what instance you assign to it in a single place. Indeed as this is not tagged as readonly, you could even change out the instante at runtime.