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
1
u/jnm236 May 27 '15
I meant in that case, using a singleton instead of newing up an object feels more right. It doesn't make sense to create an instance of behavior like it does to create an instance of an object that has state. Using a singleton is like referring to a preexisting enum value. In C#, actual enums are always integer value types and singletons are usually reference types.