I have seen some people in SO commenting that Singleton Pattern is an anti-pattern. I want to know why ?
6 Answers
Testing
One reason is that singletons aren't easy to handle with unit tests. You can't control the instantiation and by their very nature may retain state across invocations.
For that reason the principle of dependency injection is popular. Each class is injected (configured) with the classes they need to function (rather than derive via singleton accessors) and so tests can control which dependent class instances to use (and provide mocks if required).
Frameworks such as Spring will control the lifecycle of their objects and often create singletons, but these objects are injected into their dependent objects by the framework. Thus the codebase itself doesn't treat the objects as singletons.
e.g. rather than this (for example)
public class Portfolio {
private Calculator calc = Calculator.getCalculator();
}
you would inject the calculator:
public class Portfolio {
public Portfolio(Calculator c) {
this.calc = c;
}
}
Thus the Portfolio
object doesn't know/care about how many instances of the Calculator
exist. Tests can inject a dummy Calculator
that make testing easy.
Concurrency
By limiting yourself to one instance of an object, the options for threading are limited. Access to the singleton object may have to be guarded (e.g. via synchronisation). If you can maintain multiple instances of those objects, then you can tailor then number of instances to the threads you have running, and increase the concurrent capabilities of your codebase.
-
2So how do the people that use singletons deal with "Testing" and "Concurrency" issues?– PacerierCommented Jun 24, 2014 at 23:53
-
With some difficulty. Tools like PowerMock can provide means of overriding singleton methods, but they're complex tools resorting to bytecode manipulation Commented Jun 25, 2014 at 7:31
My personal opinion is that it violates the single responsibility principle. Singleton objects are responsible for both their purpose and controlling the number of instances they produce which I think is wrong.
This is why a lot of people delegate the control to a factory object.
-
1I think that just makes [the interpretation of] SRP suspicious. Commented Jul 2, 2012 at 11:24
-
1Suspicious in that this clearly isn't a thing that is wrong with Singletons, but the interpretation of SRP indicates that it is. SRP (or this interpretation of it) would appear to be the guilty party. Commented Jul 2, 2012 at 12:45
-
2Singletons having mixed responsibilities and therefore reduced cohesion is definitely something wrong with the pattern imo. Commented Jul 2, 2012 at 12:57
-
4Singletons are like mini-gods in a polytheistic world, your gods will always be fighting against each other because their concerns aren't well defined, plus if they contain state, they can change their mind and their behavior changes across invocations Commented Apr 16, 2013 at 18:35
-
When optimizing designs, one should never mix state, configuration and cache principles. I often see this being the case in singletons. How do you know? Because when the cache is independent of state, it will be transparent. Even better, when consts are replaced by a configuration class (or even better interface), makes testing/developing much easier Commented Jan 6, 2021 at 11:59
[Mutable] Singleton is an anti-pattern of an anti-pattern.
The significant underlying anti-pattern is global state (or ambient state). With global state you have a big blog of dependency across your program. This does affect testing, but that's just a one part of the fallout from bad programming.
Layered upon that, Singleton adds completely unnecessary level of complexity over simply declaring mutable static
fields.
-
2Mutable static fields suffer from the same exact problem, it's global state. I fail to see how using static fields is better than a singleton. Any information about that? Commented Apr 16, 2013 at 18:33
-
2@JuanMendes As I say, straightforward mutable statics are better than singleton mutable statics because they don't have the pointless complexity. Commented Apr 17, 2013 at 12:48
-
I should review answers better before leaving a comment. 100% agree with you. It's basically an euphemism for global state, so calling it static fields at least doesn't try to embellish it. Commented Apr 17, 2013 at 16:07
Singletons as such are not necessarily an anti-pattern, but they have only few benefits and become an antipattern when they are used wrong (which happens often).
Often, singletons are not singletons at all, but "global variables in disguise". Also, often they are used when the "only one instance" property is actually not an advantage. (which again is balanced by the fact that many times the implementation is wrong at the same time).
In addition to that, they can be tricky to implement with multithreading in mind (often done wrong or inefficiently), and they lose most of their benefits if you want to control their instantiation.
If you want to have control over instantiation, you need to do it by hand at some point early in the program, but then you could just as well just create one instance of a normal object and pass that onward.
If order of destruction is of any concern, you need to manually implement this as well. A single automatic object in the main function is just so much cleaner and easier.
There are many requirements that you might have on the singleton:
- lazy initialization;
- proper disposal;
- scoping (one per thread, for example).
Typically, also, you'll have a whole lot of singletons in your app, and the Singleton pattern doesn't allow reusable code. So, if you want to implement all these concerns for all your singletons, you'll immediately see its anti-pattern quality.
Strange. It seems that the incorrect implementation of a Singleton is an "anti-pattern", not the Singleton itself.
I think we've forgotten that every program has to start somewhere. There has to be a concrete implementation of every abstraction, and eventually every dependency will eventually be resolved, or your app wouldn't be much use.
Most DI frameworks allow instantiating a class as a Singleton, it just handles that for you. If you choose to do DI yourself, injecting a singleton isn't a problem. A Singleton IS testable as well, and if you're using DI to inject it, doesn't make a class unstable.
IMO, like every other pattern out there (including DI and IoC) it's a tool. Sometimes it fits, sometimes it doesn't.