5 ms·
So Eric is sort of right although he doesn't explicitly state it: Singletons may provide a decoupling point nearly identical to dependency injection when design
by KirinDave 14y ago
So Eric is sort of right although he doesn't explicitly state it: Singletons may provide a decoupling point nearly identical to dependency injection when designed with care. But that's not really the problem, and he stops with an argument that is compelling to someone in 2002 but not so compelling for someone from 2012.
The reason we prefer non-singletons to singletons are as follows:
• Most languages do not provide very good ways to prevent singleton collision. As software has become more complex and open source's success increases the size of the average dependency tree, this problem is exacerbated.
• Singletons force you to confront all the problems shared state concurrency has to offer, with almost no support. DI objects tend to be isolated from one another and do not run into that level of complexity so soon.
• Singletons tend to make it harder to test code unless your language has a method for overriding or mocking singletons within a dynamic scope (or static type checking between types with liskov-substitutable signatures). The most classic exampe of this is one of the most prevalent singletons: your system clock.
Knowing what we know now about how successful software projects tend to be confronted with expectations of concurrency, parallelism, robustness in the face of reuse, and testability; singletons offer a lot of costs for very transient benefits.
- masklinn 14y agoSingletons also make things painful if (when?) you have to go from "one instance" to "two instances", which regularly happens.
- eamann 14y agoWhich is why they should be used sparingly, if at all. I'm not advocating we go out and start making every class a singleton, just explaining how they do serve a purpose in PHP/WordPress development.
- mikeschinkel 14y agoI support Eric here. Singleton make sense in WordPress specifically for encapsulating plugins. In WordPress plugins can never have more than one instance so it's really a moot point to expect them to be anything else. Outside of WordPress plugins, I don't currently know of cases where I'd also advocate for singletons. Yes in most other cases singletons are bad but I'm sure there are some other cases where they do make sense. And you can't prove a negative.
- mikeschinkel 14y agoIn the case of WordPress plugins which is what Eric was writing about you know they never will go from one instance to two.