Singleton - The root of all evil
2 September, 2022
4
4
0
Contributors
The ‘magical’ appearance of the Singleton pattern.
The origin of evil
Critics consider the singleton to be an anti-pattern in that it is frequently used in scenarios where it is not beneficial, introduces unnecessary restrictions in situations where a sole instance of a class is not actually required, and introduces global state into an application.
Reasons not to use it
1. Violates the bijection principle
2. Generates coupling
An implementation of the singleton pattern must provide global access to that instance.
3. It says a lot about (accidental) implementation and little about his (essential) responsibilities
4. It prevents us from writing good unit tests
5. Does not save up memory space
6. It prevents us from using dependency injection
7. It violates the instantiation contract
8. It forces us to explicitly couple to implementation
9. It hinders the creation of automated tests
10. Unique concepts are contextual
11. It is difficult to keep up in multi-threaded environments
12. Accumulates garbage that takes up memory space
13. The accumulated garbage state is the enemy of unit tests
14. Limiting the creation of new objects violates the single responsibility principle.
The single responsibility of a class is to create instances. Adding any other responsibility to any class implies violating the single responsibility principle (the S for Solid). A class should not worry about being or not being a Singleton. They should only be responsible for their commitments to business rules. In case of needing the uniqueness of these instances, this would be the responsibility of a third object in the middle such as a Factory or a Builder.
15. The cost of having a global reference is not just the coupling
16. He’s the easy friend from the party
Reasons to use it
1. It allows us to save up memory
2. It’s good for unique concepts modeling
3. It prevents us from repeating expensive initializations
Solutions
Conclusions
design
programming
code
antipatterns
patterns
singleton
clean