#784 – When Not to Use a Static Class
February 20, 2013 1 Comment
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