4 ms·
Reminds me of a colleague implementing "emailRecipients" as a field in a singleton service. The first online order got an order confirmation mail, and when a se
by bellyfullofbac 5y ago
Reminds me of a colleague implementing "emailRecipients" as a field in a singleton service. The first online order got an order confirmation mail, and when a second online order came s/he also got their confirmation mail (the field just grew and grew...).
- andix 5y agoOne more reason not to make singletons.
- Aldipower 5y agoI like the Whisky.
- andix 5y agoSingleton Malt? Me too!
- showsover 5y agoTo be fair singletons are pretty useful. You just have to understand that they're not made for mutating state.
- jaywalk 5y agoSingletons are fine and useful in many situations. You just have to understand what singletons entail, and design them correctly. If his singleton had a "SendEmail" function that accepted an Email object with To, From, Subject, Body, etc. fields, it wouldn't have been an issue.
- andix 5y agoI 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.