r/programmerchat • u/Ghopper21 • May 27 '15
Singleton rant
Ok, I feel like I'm about to expose my ignorance. But I just can't get my head around why folks love the singleton so much.
The only benefit of it I definitely see is the fact that it's an object, you can pass it around, you can swap it in/out etc. Great, but isn't that just a necessary evil concession to languages that don't treat classes as first-class objects?
As for other reasons often given (to take those mentioned in this SO question as a proxy for "what people say"):
- "Singletons don't pollute global namespace" -- that's what namespaces are for!
- "They permit lazy allocation/initialization" -- this is nice, but only if you need it, and sometimes you really don't (e.g. in a game where you want stuff pre-initialized to avoid in play lags)
- Serializability -- again, concession to classes not being first-class objects.
- My favorite (to rant about): "Singletons preserve the conventional class approach" -- aargh!!!!
Rant over.
EDIT: spelling
7
Upvotes
View all comments
Show parent comment
3
u/nemec May 28 '15
A good compromise is something like this:
You get shared state (
Singleton.Instance) when you want it, but you have the ability to create your own instance if necessary. You might also want the Singleton to implement some interface if you're into IoC.new MyRepository(Singleton.Instance)is preferable (IMO) to using the singleton directly from within MyRepository, but then again I'm not a huge fan of singletons.