Step 73: Resist the Temptation of the Singleton Pattern~ Sam Saariste
This is the 73rd step towards gaining the Programming Enlightenment series. If you didn’t learn the 72nd Step, read it.
What is Singleton Pattern?
Singleton Pattern is one of the software design pattern mentioned in the Gang Of Four’s design patterns book.
This design pattern describes restricting the instantiation of a class to one “Single” instance.
Why use Singleton Pattern?
Singleton Pattern is useful when exactly one object is needed to be used as a global instance to coordinate across the system.
Why Singleton is anti-pattern?
- The singleton classes break object-oriented design principles. We cannot inherit from a singleton class. We don’t have control over creation and we cannot do dependency injection
- The singleton classes do not allow for test-driven development. Since, we don’t have control over creation, it makes it harder to test. Without dependency injection we cannot use mock objects in our tests.
Why resist the temptation of the Singleton Pattern?
Experience shows that most singletons really do more harm than good. It makes life of developer easier on the short term, but hinders testability and harms maintainability.
- The Singleton don’t change easily as requirements change.
- Singletons cause implicit dependencies between conceptually independent units of code preventing mock implementation.
- Singleton with mutable state introduces tests being dependent on another.
- With multi-threading singleton pattern; would have to be implemented as double-checked locking pattern (DCLP). Even DCLP isn’t thread-safe in many languages.
TL;DR Restrict the use of Singleton pattern to the classes that truly must never be instantiated more than once. Don’t use singleton’s global access point from arbitrary code instead use an interface to provide it.
Go to 72nd Step
Go to the 74th step.
References:
- 97 things Every Programmer Should Know ~ Git Book
- 97 Things Every Programmer Should Know ~ Paperback
- Pros and Cons of Singleton Design ~ FreeCodeCamp
- What is so bad about singleton? ~stackoverflow
- Resist the temptation of the singleton pattern