Search code examples
c#asp.netcode-behind

Is there anything wrong with a static class which has totally unrelating, static, methods?


I am currently working with a lot of C# code-behinds which were not originally written by me. They were written as massive lumps of horrible looking code and it is now my job to sort it out.

Anyway, there are a lot of repetitions of code, in lots of different aspx.cs files. For example, there are about five code-behind files which have exactly the same piece of code repeated a lot to output some text to a file. I could have the method:

private void outputToFile(string text)

repeated in the five different code behind files.

However, I am wondering if it is bad practice or just wrong to declare a static class called something like, "MethodHub" which holds outputToFile(string text) as well as a dozen or so other methods which do not relate to each other?

The overall goal is to access these methods from a static class so I can remove effectively hundreds of lines of code in others.

Can anybody see anything wrong with this, or any problems I may run into?


Solution

  • I would suggest to abstract such an utility behaviour by introducing interface

    interface IOutputService
    {
      void Output(string data);
    }
    

    and using your implementation implement class like

    class FileOutputService : IOutputService
    {
        // ...
    }
    

    on behalf of this interface, the main point is to avoid static class because

    EDIT:

    1. It would be mess to cover logic, which uses static clas calls, by unit tests
    2. With static class it is much complex to switch a logic/behaviour easily, you have to change a logic implementation itself, for instance, you've to switch from a file output to a database output, it will be much easily to inject another service which implements common interface rather than play with potential refactoring