Step 73: Resist the Temptation of the Singleton Pattern~ Sam Saariste
What is Singleton Pattern?
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.
97 Journey Every Programmer should Accomplish
“A journey of a thousand miles begins with a single step.”
Go to 72nd Step
Step 72: Reinvent the Wheel Often~ Jason P Sage
This is the 72nd Step towards gaining the Programming Enlightenment series. If you didn’t learn the 71st Step, read it.
Go to the 74th step.
Step 74: The Road to Performance Is Littered with Dirty Code Bombs ~ Kirk Pepperdine
This is the 74th Step towards gaining the Programming Enlightenment series. If you didn’t learn the 73rd Step, read it.