Home / Companies / LogRocket / Blog / Post Details
Content Deep Dive

You’re wrong about singletons

Blog post from LogRocket

Post Details
Company
Date Published
Author
Ashley Davis
Word Count
2,744
Language
-
Hacker News Points
-
Summary

Singletons, introduced as a design pattern in the 1995 book "Design Patterns" by the "Gang of Four," have been both praised and criticized over the years, evolving from a widely accepted solution to being labeled an anti-pattern by some. Despite the backlash, singletons remain in use due to their convenience, particularly for creating global objects with a single instance, such as a dialog provider or entity repository, which streamline access and control in complex applications. The critique of singletons often centers on their hindrance to automated testing and application restructuring due to hard-coded dependencies. However, the integration of dependency injection (DI) has revitalized the use of singletons by automating the creation and wiring of dependencies, allowing developers to benefit from their convenience without the typical drawbacks. DI facilitates easier testing and application evolution by enabling mock objects to replace singletons during testing and automating the order of dependency initialization. This approach allows developers to harness the benefits of singletons while mitigating traditional issues, suggesting that singletons, when used with DI, can still be a valuable part of modern software development.