3 ms·
I strongly disagree. Singletons are most of the time a code smell. They hide dependencies, make testing hard, and enforce tight coupling. Singletons are easy t
by andix 5y ago
I strongly disagree. Singletons are most of the time a code smell. They hide dependencies, make testing hard, and enforce tight coupling.
Singletons are easy to understand, as long as they contain of one simple class. But after a few iterations of development, they tend to "capture" a lot of dependencies, which practically become singletons too. A lot of mistakes happen. And most of the time, there was no good reason to create a singleton in the first place.
see also those posts:
https://stackoverflow.com/a/138012/4249619 https://stackoverflow.com/a/138012/4249619
https://stackoverflow.com/a/142450/4249619 https://stackoverflow.com/a/142450/4249619
- dkersten 5y agoI'm of the opinion that singletons are only useful if both of the following requirements hold: 1. They MUST NOT allow more than one instance. "I don't think anyone will ever need more than one" isn't enough. Just create only one instance then. Only enforce single instance if there is a requirement for it. For example, a logger is a bad singleton because you could conceivably want more than one instance. Something that requires exclusive access to some hardware may be a good candidate though. 2. The instance must be globally accessible. Many things don't need to be globally accessible though. So unless you need a global enforced-single-instance of something, which in my ~20 years of programming is rarely needed, a singleton is a bad choice. In my experience, many times someone wanted only one instance, some time later it turns out that actually multiple instances would be useful after all (separate loggers for separate types of logs for example). In most cases where singletons are used, a simple global would have sufficed. If you only want one instance, then create only one instance. If you need lifecycle management, then do something for that. Those SO posts cover it nicely.