4 ms·
As a simple C# (and previously VB.NET, sorry not sorry) wageslave, I've never understood the disdain towards singletons. A single static class that is reference
by mdb31 4y ago
As a simple C# (and previously VB.NET, sorry not sorry) wageslave, I've never understood the disdain towards singletons. A single static class that is referenced all over the place (or, alternatively, some huge state object): sure, don't do that.
But given a semi-decent dependency injection framework, and a choice of lifetimes like 'singleton' (only one per container), 'transient' (as many per container as required per type) and 'scoped' (as many per container as required for transactions), do I really need to feel bad about the first choice?
My app only has a single task scheduler: that's sort-of important, as otherwise there is just chaos. So that's a singleton. Maybe not the same singleton depending on whether I'm running a test or the actual production app, but a singleton nonetheless. So what, exactly, is the big issue with that?
- strictfp 4y agoHaving one instance of a class that's being passed around isn't bad. The singleton pattern with what's effectively a global variable , accessible from anywhere, is bad though.
- mdb31 4y agoSure, as I said "a single static class: don't do that" -- however, the definition of a singleton, as per the GoF, is just "something that restricts the instantiation of a class to one instance". Nothing about global visibility, and again, any decent dependency-injection framework should manage that well enough. So, still mystified about all the singleton-hate here!
- kjeetgill 4y agoI mean, you're right. I came to much the same pattern myself. Much of the singleton hate is from everyone who hasn't figured out, seen, or works with a language that doesn't support "the good way" to do singletons. Alternatively, you could say this _similar, but different_ approach correctly acknowledges and similarly avoids _actual_ problematic singletons. We can all be friends here :D.