#784 – When Not to Use a Static Class

You can create a static class as a container for a collection of static utility methods that you can invoke without having to create an instance of some object.

There are a few drawbacks to using static classes, however:

  • Global data and concurrency problems – static data within a static class is effectively global data, which can lead to concurrency problems when multiple threads access/change the static data
  • Allure of monolothic classes – it’s easy to end up with large static classes containing a bunch of unrelated methods
  • Can’t extend behavior of a static class – because you can’t inherit from a static class, you can’t extend the class’ behavior by using inheritance
  • Harder to isolate, for testing purposes – since we can’t treat the static class as an interface, we can’t swap out the actual implementation for a mocked version of the class
Advertisements

#783 – When to Create a Static Class

A static class is a class that contains only static members and cannot be instantiated.  You don’t create an instance of the class, but rather just access its members directly.

    public static class DogUtil
    {
        public static void DoSomething()
        {
            Console.WriteLine("I'm doing something");
        }
    }
    public static class DogUtil
    {
        public static void DoSomething()
        {
            Console.WriteLine("I'm doing something");
        }
    }

You typically use a static class to hold a collection of methods that are utility methods and don’t need to act upon data that is persisted within a particular object.

As an example, the System.Math class in .NET contains a lot of math utility methods.  Each method operates in a stateless way.  That is, the method accepts one or more parameters, does some calculations, and returns a result.