Most people here and on StackOverflow agree that Singletons are evil.
The main explanation I’ve come across against the use of Singletons, is they fact that they provide a global point of access to an object.
I admit to not understand why this is a bad thing. It’s very convenient to be able to access an important and useful object from anywhere in your code, without having to ‘pass it around’ in order to get it.
So why is a global point of access in OOP a bad thing? Not only with Singletons, but generally. Please give concrete examples.
4
Disadvantages are that:
-
it is not obvious where it is used
-
when you use something that uses it, you cannot supply alternatives (esp. when testing, you do not want to use eg. real credit card payment)
-
when you decide that you want two contexts in which it should be unique you must rewrite every usage.
These disadvantages are sometimes acceptable, sometimes not.
Note that problem is not in the fact that only one instance is used (it often is very usefull), but in it being hardcoded and invisible from outside.
3