2049

The singleton pattern is a fully paid up member of the GoF's patterns book, but it lately seems rather orphaned by the developer world. I still use quite a lot of singletons, especially for factory classes, and while you have to be a bit careful about multithreading issues (like any class actually), I fail to see why they are so awful.

Stack Overflow especially seems to assume that everyone agrees that Singletons are evil. Why?

Please support your answers with "facts, references, or specific expertise"

serv-inc
  • 29,557
  • 9
  • 128
  • 146
Ewan Makepeace
  • 5,248
  • 8
  • 29
  • 31
  • 6
    I have to say that using a singleton design has burned me recently as I have tried to adapt the code. As I do it in my free time, I'm almost too lazy to refactor this. Bad news for productivity. – Marcin Oct 10 '08 at 18:49
  • 76
    There's a lot of 'cons' in the answers, but I'd also like to see some good examples of when the pattern is good, to contrast with the bad... – DGM Oct 15 '08 at 06:03
  • I don't agree that Singletons are bad. But I would agree that they seem to be overused! – Jeach Feb 18 '10 at 15:23
  • I think the reason they get a bad rep is because they are overused and the people who implement them have too many static methods. Instead of using an interface, they use a class. That is a typical singleton implementation and that is a bad implementation! – Jeach Feb 18 '10 at 15:59
  • 50
    I wrote a blog post on the subject a few months ago: http://jalf.dk/blog/2010/03/singletons-solving-problems-you-didnt-know-you-never-had-since-1995/ -- and let me just say it outright. I can't personally think of a single situation where a singleton is the right solution. That doesn't mean such a situation does not exist, but... calling them rare is an understatement. – jalf Jun 25 '10 at 02:12
  • 1
    See also, on programmers: **[The Singleton Pattern](http://programmers.stackexchange.com/questions/37249/the-singleton-pattern)** – hippietrail Mar 19 '12 at 19:59
  • 1
    @jalf I disagree. Just because it is a singleton does not mean you have to access it through `MySingleton.sharedInstance()` everywhere it is used. Pass it as an argument e.g. See my post: http://assoc.tumblr.com/post/51302471844/the-misunderstood-singleton – Erik Engheim May 25 '13 at 14:48
  • 9
    @AdamSmith it doesn't mean you *have* to, but it means you *can* access it like that. And if you don't intend to access it like that, then there's little reason to make it a singleton in the first place. So your argument is effectively "there's no harm in making a singleton if we don't *treat* it as a singleton. Yeah, great. My car also doesn't pollute if I don't drive in it. But then it's easier to just not acquire a car in the first place. ;) (full disclosure: I don't actually have a car) – jalf May 26 '13 at 09:55
  • 1
    @AdamSmith I'm not on tumblr so I can't comment on your post directly, but really, you're saying that a singleton is suitable for representing things that there are **usually** just one of? Really? Really? I rest my case. *Don't use singletons*. And if you do use them, at least come up with a situation where they're beneficial. – jalf May 26 '13 at 09:57
  • 3
    @hippietrail: The discussion you linked is a duplicate. Look here instead: http://programmers.stackexchange.com/questions/252/when-is-singleton-appropriate/247340 – donquixote Jul 09 '14 at 05:55
  • 3
    Erich Gamma, member of the GoF, in a interview about a new edition of the book says "I'm in favor of dropping Singleton. Its use is almost always a design smell.)" http://www.informit.com/articles/article.aspx?p=1404056 – neves Oct 24 '14 at 14:30
  • 3
    It would be worthwhile reading Robert C Martin's blog post [The Little Singleton](http://blog.8thlight.com/uncle-bob/2015/06/30/the-little-singleton.html) which demolishes some of the arguments against singletons, while still pointing out some of the real issues and concluding with *"most of the time we don't want to [use them]"*. – Simba Aug 19 '15 at 10:23
  • 39
    The worst part of this whole topic is that the people who hate singletons rarely give concrete suggestions for what to use instead. The links to journal articles and self-published blogs all through this SO article, for example, go on and on about why *not* to use singletons (and they're all excellent reasons), but they're extremely slim on replacements. Lots of handwaving, though. Those of us trying to teach new programmers why not to use singletons don't have many good third-party counterexamples to point to, only contrived examples. It's wearying. – Ti Strga Sep 08 '15 at 18:32
  • 2
    I think it's a bad idea to have an overarching opinion on a design pattern. ALL design patterns have advantages and disadvantages that often depend on the use case. – Andy Dec 11 '15 at 17:08
  • 1
    @TiStrga I hear ya and my story may be relevant: As an android developer, I was super against Singletons for a long time; people only /think/ they have a singleton, but Android OS does not guarantee you'll have the same processID when returning to the foreground so loads of ANR and where is your singleton god now? However, we /are/ assured of the same appId/UID; the Application is the only tru singleton. Enter Dagger 2, where pretty much everything w/a scope annotation in the DI graph is singleton by default--and it's a real singleton. Now I love 'em =] – anthropic android Aug 12 '16 at 02:56
  • 3
    I'm gonna vent right now: people who closed this are really just self-inflated. You gotta understand, if the best people in C++ (i.e. Herb Sutter and Bjarne Stroustrup) say that singletons are bad, then you should stop and wonder if that's "just an opinion". And as a programmer facing something like this, you wanna hear why it's good and why it's bad and form your own opinion. So, no, this is not opinion based. The person asking the question will form their opinion, but the people answering should answer in facts. Absolutely no reason to close this. – Enn Michael Oct 22 '16 at 17:38
  • [Here](https://www.michaelsafyan.com/tech/design/patterns/singleton) is a good read on singleton being an anti-pattern. It describes the pain points very well. – RBT Oct 25 '16 at 06:31
  • @jalf the link says 404? – Vikas Prasad Aug 25 '17 at 17:25
  • just wrote a long answer to this question https://stackoverflow.com/questions/45967619/dependency-injector-classes-static-singleton-vs-parameter/45969179#45969179 – Shahar Shokrani Sep 07 '17 at 18:35
  • @TiStrga Uh, just don't use anything to replace the singleton? What's wrong with creating an object with `new`? `new Xxx` has similar testability problems as `Xxx.getInstance()` but you automatically use it in less places, making it practical to refactor if you need unittestability. – user253751 Jan 12 '18 at 04:53
  • immibis, that's exactly the sort of handwaving I had in mind when I wrote my complaint... Also, you don't need to be sarcastic to _me_, since I'm not the one defending the use of singletons. I think you're wrong with your assertion of "automatically use it in less places," but this isn't an argument I care about. – Ti Strga Jan 16 '18 at 17:25
  • @TiStrga Rather then use singletons, you use dependency injection, registering your single-instance dependency in singleton scope in the IoC-container. It's incredibly easy if you're already using DI or designing new architecture. – sdds Apr 06 '19 at 09:13
  • A copy of the blog post of @jalf can be found here: [Singletons: Solving problems you didn't know you never had since 1995 (Wayback Machine copy)](https://web.archive.org/web/20160716061218/http://jalf.dk/blog/2010/03/singletons-solving-problems-you-didnt-know-you-never-had-since-1995/) – Georgy May 22 '19 at 09:33
  • There is absolutely nothing wrong with singletons if you use them correctly - use them only if really needed, make them polymorphic so that you can mock them easily, create fresh new and destroy them in each unittest where they are needed, do not use them in threads unless properly mutexed. The holy war against singletons is fought only by theoreticians. – V.K. Aug 21 '19 at 11:20
  • [Code examples of Design Patterns in various languages: C#, C++, Go, Java, JavaScript, Python, and Swift.](https://github.com/MilovanTomasevic/Design-Patterns) – Milovan Tomašević Apr 18 '21 at 19:15

36 Answers36

1343

Paraphrased from Brian Button:

  1. They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.

  2. They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.

  3. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.

  4. They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.

Panagiotis Koursaris
  • 3,025
  • 2
  • 20
  • 40
Jim Burger
  • 4,229
  • 1
  • 22
  • 27
  • 341
    I disagree with you. Since comments are allowed only 600 chars, I have written a Blog Post to comment on this, please see the link below. http://jorudolph.wordpress.com/2009/11/22/singleton-considerations/ – Johannes Rudolph Nov 22 '09 at 14:35
  • 61
    On point 1 and 4, I think singletons are useful, and in fact almost perfect for caching data (especially from a DB). The increase in performance far outway the complexities involved in modeling unit tests. – Dai Bok Dec 02 '09 at 15:46
  • 58
    @Dai Bok: "caching data (especially from a DB)" use the proxy pattern to do this... – paxos1977 Jan 13 '10 at 23:08
  • 1
    Ok, just looked into it, the problem is particulaly with web apps is that that if the proxy gets out scope (garbage collected or something), this cache memory may be deallocated? I may ask a stupid question next. – Dai Bok Jan 19 '10 at 14:51
  • 59
    Wow, great responses. I probably used overly agressive wording here, so please keep in mind I was answering a negatively geared question. My answer was meant to be a short list of the 'anti patterns' that occur from bad Singleton usage. Full disclosure; I too use Singletons from time to time. There are more neutrally posed questions on SO that would make excellent forums for when Singletons can be considered a good idea. For instance, http://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton – Jim Burger Apr 16 '10 at 06:23
  • 8
    Bad opinions on Singletons are a result of OO. Static/global data still has its place, just not wrapped in metanonsense. – Matt Joiner Aug 04 '10 at 09:08
  • 1
    @Matt fair point indeed, some languages tackle this issue better than others. Certainly the rhetoric around Singletons of late focus on the class oriented and object oriented languages. – Jim Burger Aug 05 '10 at 01:29
  • 21
    They aren't so great for caching in an multithreaded environment. You can easily defeat a cache with multiple threads fighting over a limited resource. [maintained by a singleton] – monksy Mar 28 '11 at 14:56
  • 2
    in a sense DI containers are singletons. Singleton of singletons. is that bad also? they are also tricky to test. – DarthVader May 29 '12 at 04:57
  • I think you are using a strawman argument. You would get the same problem you describe if the objects were not sigletons but created inside the functions that used them. Both problems are solved by dependecy injection. See me blog: http://assoc.tumblr.com/post/51302471844/the-misunderstood-singleton – Erik Engheim May 25 '13 at 14:44
  • 2
    I disagree with these four points. May be singleton is a bad choice at some point. But these four points aren't the actual reason. We can easily fix these things(4 points) with singleton pattern itself. – Sri Nov 10 '13 at 11:58
  • @Sriram but the whole point is what is so bad about singletons, so if you say those 4 points do not break the pattern then you're actually agreeing with the answer to the question - it's how people abuse them! By the way, for the first point, if you need global vars, the [**Toolbox**](http://programmers.stackexchange.com/a/218322/4261) sounds like a great solution to me. – cregox Nov 16 '13 at 10:07
  • @cHao I said "usually" in my blog. It is up to you how you want to model your computer system. Filesystems like XFS present your multiple physical hardrives as one. There are no iron rules for what you should make a singleton. Nothing prevents you from being pragmatic. If you read my blog you should see that my examples are all about being pragmatic. – Erik Engheim Feb 17 '14 at 13:22
  • 1
    Great explanation! I think the only valid reason for a singleton is if your framework/environment already sucks, and you have no way of avoiding the global state and global access point issues. But even then you can do something less evil than the usual singleton implementation. – donquixote Jul 09 '14 at 04:08
  • Minus one. This answer is blaming singletons for the limitations of some test framework, and wrapping it into more dogmatic bs. – ZunTzu Nov 19 '15 at 14:41
  • I do use singletons and the problem that I want to solve is: I do not have control over initialization order. When classes are created, no environment exists. When Application is created, the environment is not yet initialized. And when UI appears on the screen, it's a bit too late. – 18446744073709551615 Feb 21 '16 at 12:45
  • 2
    Plus one, but the second point is not correct. Constructors in classes control creation of the object and they are not considered bad. – Krzysztof Krasoń Apr 09 '16 at 06:10
  • 1
    So, simply speaking `window` object is javascript is singleton right? – CodeYogi Apr 15 '16 at 16:16
  • so you mean in a tearDown of a test case, you would have to undo what you just did (in the Singleton)? I thought testcase are independent. – Honey Jan 06 '17 at 22:24
  • Regarding point #2, ever hear of the Information Expert pattern (part of the GRASP patterns)? There's nothing wrong with an object creating itself if it has the necessary information to do so. – iupchris10 Jan 13 '17 at 17:51
  • 1
    Sounds very dogmatic. – Bill Rosmus May 18 '17 at 03:57
  • I found pass a global instance 10 levels down in the call stack very painful, and that is where the singleton comes to rescue - easily get access to something whereever you want it, as to tests, well, we use RAII to make sure the crime scene is recovered – baye Apr 09 '19 at 00:22
  • For 1., pointing to examples of how a pattern may be misused is not an argument against using a pattern (its like saying that dangerous driving is an argument against cars), 2. this is a mischaracterization of the single responsibility principal, 3. this is an argument against local instances/references not singletons (the singleton instance could still be passed as a parameter and hence faked while a local instance of a normal class can't be), 4. this can easily be addressed in testing by constructing the singleton instance directly rather than using the static instance member. – Trevor Jun 15 '20 at 12:13
  • How are you supposed to share logic between two parts of the application if not for singletons. Are you going to pass all needed variables in the constructors (tightly coupled...?). Look at all the all moders todays `IoC` containers - i'ts basically a singleton box. And all services that an application uses are usually of singleton instances - which improves testability. MVVM in the C# world means you put all logic into singletons. Ask yourself why react needed global state management tools - when it i'ts traditional core data flow is strict downwards. – lolelo Jun 21 '20 at 10:29
  • I am proud of the internet for leaving the number of upvotes on this post alone. It's important that we work together in these ways, even as strangers. – simonw16 Apr 30 '21 at 06:52
471

Singletons solve one (and only one) problem.

Resource Contention.

If you have some resource that

(1) can only have a single instance, and

(2) you need to manage that single instance,

you need a singleton.

There aren't many examples. A log file is the big one. You don't want to just abandon a single log file. You want to flush, sync and close it properly. This is an example of a single shared resource that has to be managed.

It's rare that you need a singleton. The reason they're bad is that they feel like a global and they're a fully paid up member of the GoF Design Patterns book.

When you think you need a global, you're probably making a terrible design mistake.

Kick Buttowski
  • 6,371
  • 12
  • 34
  • 54
S.Lott
  • 359,791
  • 75
  • 487
  • 757
  • 49
    Hardware is also an example right? Embedded systems have lots of hardware that might use singletons - or maybe one big one? – Jeff Apr 28 '09 at 00:29
  • 180
    Totally agree. There's a lot of determined "this practice is bad" talk floating around without any recognition that the practice may have its place. Often, the practice is only "bad" because it's frequently misused. There's nothing inherently wrong with the Singleton pattern as long as it's applied appropriately. – Damovisa Apr 28 '09 at 00:34
  • 54
    Real, by-principle singletons are very rare (and a printer queue certainly isn't one, and neither is a log file - see log4j). More often than not, hardware is a singleton by coincidence rather than by principle. All hardware connected to a PC is at best a coincidental singleton (think multiple monitors, mice, printers, sound cards). Even a 500 mio $ particle detector is a singleton by coincidence and budget constraints - which don't apply in software, thus: no singleton. In telecommunications, neither phone number nor the physical phone are singletons (think ISDN, call center). – digitalarbeiter Apr 07 '10 at 14:04
  • 24
    Hardware may have only one instance of a variety of resources, but hardware isn't software. There's no reason that a single serial port on a development board should be modeled as a Singleton. Indeed, modeling it so will only make it harder to port to the new board that has two ports! – dash-tom-bang Apr 07 '10 at 19:02
  • 1
    The single serial port **is** a Singleton. Only one. Multiple instances must be absolutely forbidden. When you move to a board with exactly two ports you have a complex problem, but it amounts to "two Singletons" since you have absolutely limited resources: two ports. – S.Lott Apr 08 '10 at 01:47
  • 20
    So you'd write two identical classes, duplicating a lot of code, just so you can have two singletons representing two ports? How about just using two global SerialPort objects? How about not modelling the hardware as classes at all? And why would you use singletons, which also imply global access? Do you want *every* function in your code to be able to access the serial port? – jalf Jun 25 '10 at 02:31
  • 4
    Two serial ports violates the **Singleton** principle. Now there are as many instances as you have hardware, which is not a **Singleton**. It's just a class bound to hardware. – S.Lott Jun 25 '10 at 11:06
  • 5
    To enforce a rule that only one instance at a time can exist is not the same as _needing_ a singlton. Most DI-framework support single creation which gives you all the benifits of testability and enforces one instance. – Rune FS Aug 25 '10 at 10:57
  • @Rune FS. You only *need* a Singleton when you have the situation that only one instance can exist at a time. – S.Lott Aug 25 '10 at 11:52
  • 9
    @S.Lott I disagree on the _need_ part. a singleton is a solution to that problem but not the _only_ solution to that problem and since singletons easily cause testability and coupling issues I'd say it's a poor solution even to the problem it was designed to solve. There's at most a _can use_ but there no _need_ – Rune FS Aug 25 '10 at 12:28
  • 6
    @Rune FS: I think you might be confusing cause and effect, necessary and sufficient. Singleton design is not equivalent to "only one instance can exist". Singleton does not always follow from "only one instance can exist", since -- as you say -- there may be alternatives. However, "only one instance can exist" is *necessary* for Singleton designs, since no other purpose can possibly exist for Singleton. "only one instance can exist" is not *sufficient* for Singleton design, since there are alternatives. – S.Lott Aug 25 '10 at 13:46
  • 3
    @S.Lott: Well let me be very specific then because it seems I've been unclear my original comment could have been: "If you have some resource that (1) can only have a single instance, and (2) you need to manage that single instance, you need a Singleton." is a falsum since you can solve that problem with out a singleton so there's no _need_ for a singleton as you put it – Rune FS Aug 25 '10 at 14:01
  • 1
    @Rune FS: There is a need. But it isn not **sufficient** reason to use a singleton. It's necessary, but not -- as you point out -- sufficient. Need == Necessity. Necessity != Sufficiency. – S.Lott Aug 25 '10 at 17:03
  • 3
    There's no need because you can get by without so the singleton isn't necessary. It never is but a lot of developers seems to think they need a singleton when actually they don't. Which is my point in stressing that they are neither needed nor nesecarry – Rune FS Aug 25 '10 at 17:16
  • 1
    @void.pointer - if the requirements change later, you can refactor. If the singleton pattern can reduce your code size by not having to pass the darn thing around as an argument to a lot of method calls, then why not go for the simpler approach? (Unless you're sure you'll need that extra port or that it would be very hard to refactor later.) – antinome Sep 17 '14 at 19:02
  • 1
    Hehe, the entire service/factory model in angular is built around singletons and works beautifully. Anything view-oriented like a controller or a view is an instance with a scope, anything else is a singleton and used as a model with state or as service methods. Having a singleton data model allows all views to represent the same data in different ways. – FlavorScape Oct 24 '14 at 22:40
  • 1
    This purpose can also be solved by Object Pool pattetn isn't it? – Abdul Rahman K Jul 18 '15 at 11:07
  • 2
    this answer is precisely correct, until it says ... **rare** ... rare, WTF?! there are about 2 billion (I believe) ios and android phones on the planet. all device programming - the entirety of it - is about nothing other than singletons. (for exactly the reasons perfectly explained in this answer.) I mean the **app is a singleton** for goodness sake, in iOS (what else could it be?) **every service** (like gps, time, "the screen", etc etc) on a phone is a singleton. i guess there are still some mainframe fortran jobs, but "rare"?! – Fattie Sep 18 '15 at 20:53
  • 5
    @JoeBlow I think the definition of singleton is getting warped. While all those things may *often* only be represented by a single class instance, I don't think that's enough to qualify for being a singleton. If they truly were singletons, then we would never be able to have more than one screen, camera, etc. on our phones unless they add classes like Screen2 or Camera2 or whatever they may be, and then required devs to call those singletons explicitly. But I haven't done programming on a phone before... is that really how they do it? – tobii Jan 28 '16 at 00:13
  • Can we consider `window` and `document` objects in javascripts as singleton? – CodeYogi Apr 15 '16 at 16:18
  • 1
    Note that computers traditionally have singleton-like support for *monitors* and that's why multi-monitor support is *still weird and buggy 20 years later* - because it's emulating a single big monitor in order to please the singleton design! (I mean multiple monitors on a single seat; multiseat works differently, but only because they managed to find a way to give each seat its own set of singletons) – user253751 Jan 12 '18 at 04:56
  • @Jeff having one log, or one serial port is not a good reason. Having existing code for “The log” or “The serial port” may be. If it is to difficult to fix the legacy code, then use a singleton as its factory. However you can also separate the roles of factory and one-ness (that way you can have two-ness, and three-ness). – ctrl-alt-delor Jun 06 '19 at 12:02
  • `When you think you need a global, you're probably making a terrible design mistake.` you said. But I'm building an application, user must login to use, and when user logged in, I need to retrieve user informations in any screen to present to user interface (it's about 10-20 screens). What design should I use if not`singleton`? If I pass user to every single screen like dependency injection, it seems terrible, isn't it ? – Tung Vu Duc Jul 02 '19 at 08:51
367

Some coding snobs look down on them as just a glorified global. In the same way that many people hate the goto statement there are others that hate the idea of ever using a global. I have seen several developers go to extraordinary lengths to avoid a global because they considered using one as an admission of failure. Strange but true.

In practice the Singleton pattern is just a programming technique that is a useful part of your toolkit of concepts. From time to time you might find it is the ideal solution and so use it. But using it just so you can boast about using a design pattern is just as stupid as refusing to ever use it because it is just a global.

Felixyz
  • 18,843
  • 13
  • 64
  • 60
Phil Wright
  • 21,516
  • 12
  • 77
  • 129
  • 17
    The failure I see in Singleton is that folks use them instead of globals because they're somehow "better." The problem is (as I see it), that the things that Singleton brings to the table in these cases are irrelevant. (Construct-on-first-use is trivial to implement in a non-singleton, for example, even if it's not actually using the constructor to do it.) – dash-tom-bang Apr 07 '10 at 19:10
  • 21
    The reason "we" look down upon them is that "we" very frequently see them used wrong, and way too often. "We" do know that they have their place of cause. – Bjarke Freund-Hansen Feb 10 '12 at 10:59
  • 5
    @Phil, You stated "from time to time you might find it is the ideal solution and so use it". Ok, so exactly in *which* case would we find a singleton useful? – Pacerier Jun 25 '14 at 01:37
  • 25
    @Pacerier, whenever all of following conditions hold: (1) you only need one of something, (2) you need to pass that one thing as an argument in a large number of method calls, (3) you are willing to accept a chance of having to refactor someday in exchange for an immediate reduction in the size and complexity of your code by not passing the darn thing around everywhere. – antinome Sep 17 '14 at 18:37
  • 19
    I don't feel that this answers anything, it just says that 'sometimes it might fit, other times it may not'. OK, but why, and when? What makes this answer more than an [argument to moderation](http://en.wikipedia.org/wiki/Argument_to_moderation)? – Guildenstern Oct 24 '14 at 18:59
  • @antinome Totally agree. Why have many objects floating around in memory when you can get by with just one. It's a good alternative for example if you aren't able to support static methods for some common code. – etech Feb 22 '17 at 17:31
  • Like the goto, the singleton (and globals) might have their place where they can be used, but like all bad habits, they should not be used. There is neither a good discipline in programming for avoiding improper usage, nor is there a good set of use-cases that can define where the singleton is the correct pattern. The history of software development has conclusively proven that anything that can be misused will be misused to the greatest extent possible. – scott m gardner Feb 14 '19 at 02:27
  • 1
    @MarekR It is actually a very reasonable answer if you read past the first three words. – Big Temp May 27 '20 at 23:45
  • @BigTemp it is not. This answer is based on emotions and habits. Where answer against refers to technical and architecture problems singleton introduces. Can you point out real technical argument here? Yes there is valid argument for singletons, but this answer do not provide it in clear technical way. – Marek R May 28 '20 at 06:52
226

Misko Hevery, from Google, has some interesting articles on exactly this topic...

Singletons are Pathological Liars has a unit testing example that illustrates how singletons can make it difficult to figure out dependency chains and start or test an application. It is a fairly extreme example of abuse, but the point that he makes is still valid:

Singletons are nothing more than global state. Global state makes it so your objects can secretly get hold of things which are not declared in their APIs, and, as a result, Singletons make your APIs into pathological liars.

Where have all the Singletons Gone makes the point that dependency injection has made it easy to get instances to constructors that require them, which alleviates the underlying need behind the bad, global Singletons decried in the first article.

user3768649
  • 169
  • 2
  • 7
jason
  • 656
  • 1
  • 7
  • 15
  • 8
    Misko's articles on the subject are the best thing going around on it at the moment. – Chris Mayer Sep 26 '08 at 06:34
  • 24
    The first link doesn't actually address a problem with singletons, but rather assuming a static dependency inside the class. It's possible to fix the given example by passing in parameters, yet still use singletons. – DGM Oct 15 '08 at 13:57
  • 18
    @DGM: Exactly - in fact, there is a huge logical disconnect between the 'rationale' part of the article, and the 'Singletons are the cause' part. – Harper Shelby Dec 29 '08 at 20:56
  • 1
    Misko's CreditCard article is an *extreme* example of misuse of this pattern. – Alex Apr 25 '12 at 13:17
  • 2
    Reading the second article Singletons are actually part of the object model described. However, instead of being accessible globally these are private to the Factory objects. – FruitBreak Oct 30 '12 at 16:41
  • If somebody thinking is here, he would surely come to the conclusion that there actually is a singleton out there. – luke1985 Sep 17 '13 at 14:18
  • @jason, Somehow the links wouldn't load. The get stuck in perpetual loading... – Pacerier Jun 27 '14 at 17:27
  • In the case of hardware peripherals (e.g. SPI, Timer) on a microcontroller, there is a "global state" (i.e. peripheral registers) independent of the CPU-run program. It would likely be preferable to enforce that only one instance of a "mirror object" (i.e. singleton) of that external global state can be instantiated, so that two different threads can't create "mirrors" and step on each other without realizing it. This would enable the singleton to "cache" reliable summaries of the HW state (e.g. bool isInit), so that callers don't have to manually verify the HW state on every call. ... – abc Feb 22 '20 at 17:52
  • ... Now whether the singleton is accessed by a global instance or static call (e.g. #include "Spi.h", ... Spi::read()) vs passing a local instance of the singleton object is another matter. The singleton can be enforced by having a static object of itself and a private constructor, or by deleting the constructor in the case of a "static class" (though that would prevent passing around a local object). – abc Feb 22 '20 at 17:54
131

I think the confusion is caused by the fact that people don't know the real application of the Singleton pattern. I can't stress this enough. Singleton is not a pattern to wrap globals. Singleton pattern should only be used to guarantee that one and only one instance of a given class exists during run time.

People think Singleton is evil because they are using it for globals. It is because of this confusion that Singleton is looked down upon. Please, don't confuse Singletons and globals. If used for the purpose it was intended for, you will gain extreme benefits from the Singleton pattern.

Felixyz
  • 18,843
  • 13
  • 64
  • 60
Cem Catikkas
  • 6,961
  • 4
  • 26
  • 33
  • 21
    What is that one instance, available throughout the app? Oh. *Global*. "Singleton is **not** a pattern to wrap globals" is either naive or misleading, as *by definition*, the pattern wraps a class around a global instance. – cHao Feb 19 '13 at 07:10
  • 27
    Of course you're free to create one instance of the class when your application starts, and inject that instance, through an interface, into anything that uses it. The implementation shouldn't care that there can be only one. – Scott Whitlock Mar 31 '14 at 19:33
  • 1
    There is huge difference between having global variable (reference to a memory without any access control) and having singleton (reference to a memory with access control). – Dainius Oct 24 '14 at 11:27
  • 4
    @Dainius: There's really not, in the end. Sure, you don't get to arbitrarily replace the instance with another. (Except for those facepalm-inducing moments when *you do*. I've actually seen `setInstance` methods before.) That hardly matters, though -- that weenie that "needed" a singleton also didn't know a freaking thing about encapsulation or what's wrong with mutable global state, so he helpfully(?) provided setters for every. single. field. (And yes, this happens. A *lot*. Nearly every singleton i've ever seen in the wild was mutable by design, and often embarassingly so.) – cHao Jan 08 '15 at 05:42
  • It should be mutable by design, if you have immutable singleton its probably can be replaced by const object, or if it doesn't have any fields than it's just utility lib. From OS view singleton and global variable might be same, but at least from developer perspective it's huge difference. Have you tried to debug program, who use singleton and global vars to catch a bug? Setters is completely different problem, I have seen pure data objects that only methods was set and get and how does this related to singleton? Bad design is bad design. – Dainius Jan 09 '15 at 07:16
  • 1
    @Dainius: It's related in that you often see the two together, because they're both closely related to a procedural mindset. Some people consider data "stuff to act on" rather than "stuff that acts". Which is an entirely valid POV, IMO, as long as you acknowledge and embrace it. But these people instead shoehorn the code into objects and classes in order to avoid the disapproving stares of the OO zealots. And that's when it all starts going to hell. – cHao Jan 09 '15 at 16:28
  • You gain next to nothing from global state that's hidden away inside a class. In fact, one thing you inherently lose is testability. At least with honest-to-goodness globals, or even singleton-with-setters-for-everything globals, you have a way to reset the world to a known state. A "well-designed" singleton typically doesn't even give you that. – cHao Jan 09 '15 at 16:41
  • To many people wrongly use inheritance in OO programming, should we declare it bad way and say that you always should use composition? – Dainius Jan 10 '15 at 19:21
  • 4
    @Dainius: To a large degree, we already have. "Prefer composition over inheritance" has been a thing for quite a while now. When inheritance *is* demonstrably the best solution, though, you are of course free to use it. Same thing with singletons, globals, threading, `goto`, etc. They might *work* in many cases, but frankly, "works" isn't enough -- if you want to go against conventional wisdom, you had better be able to demonstrate how your approach is *better* than the conventional solutions. And i've yet to see such a case for the Singleton pattern. – cHao Jan 10 '15 at 23:20
  • 2
    I totally agree that there isn't many cases when singleton is best way, but I also saw designs, where to avoid singleton was made some horrible (for maintenance/speed) decision. Have you use static class member - that's a singleton. Is it used very often - no, is it useful sometime - yes. Because people are using monster cars to go to work, you don't say these cars are bad, you educate people to use appropriate cars for going to work and for other kind of trips, don't you. – Dainius Jan 12 '15 at 08:50
  • 3
    Lest we talk past each other, i'm not just talking about a globally available instance. There are plenty of cases for that. What i'm talking about (particularly when i say "capital-S Singleton") is the GoF's Singleton pattern, which embeds that single global instance in the class itself, exposes it via a `getInstance` or similarly named method, and prevents the existence of a second instance. Frankly, at that point, you might as well not even have the *one* instance. – cHao Jan 12 '15 at 12:30
74

One rather bad thing about singletons is that you can't extend them very easily. You basically have to build in some kind of decorator pattern or some such thing if you want to change their behavior. Also, if one day you want to have multiple ways of doing that one thing, it can be rather painful to change, depending on how you lay out your code.

One thing to note, if you DO use singletons, try to pass them in to whoever needs them rather than have them access it directly... Otherwise if you ever choose to have multiple ways of doing the thing that singleton does, it will be rather difficult to change as each class embeds a dependency if it accesses the singleton directly.

So basically:

public MyConstructor(Singleton singleton) {
    this.singleton = singleton;
}

rather than:

public MyConstructor() {
    this.singleton = Singleton.getInstance();
}

I believe this sort of pattern is called dependency injection and is generally considered a good thing.

Like any pattern though... Think about it and consider if its use in the given situation is inappropriate or not... Rules are made to be broken usually, and patterns should not be applied willy nilly without thought.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Mike Stone
  • 42,897
  • 27
  • 110
  • 137
  • 18
    Heh, if you do this everywhere, then you would have to pass around a reference to the singelton everywhere also, and thus you don't have a singleton any more. :) (Which is usually a good thing IMO.) – Bjarke Freund-Hansen Feb 10 '12 at 11:02
  • 3
    @BjarkeFreund-Hansen - Nonsense, what are you talking about? A singleton is simply an instance of a class that is instatiated once. Referencing such an Singleton doesn't copy the actual object, it just references it - you still got the same object (read: Singleton). – M. Mimpen Dec 11 '13 at 10:35
  • 2
    @M.Mimpen: No, a capital-S Singleton (which is what is being discussed here) is an instance of a class that (a) *guarantees* that only one instance will ever exist, and (b) is accessed via the class's own built-in global point of access. If you have declared that nothing should be calling `getInstance()`, then (b) is not quite true anymore. – cHao Feb 17 '14 at 14:50
  • 3
    @cHao I don't follow you or you don't understand to whom I comment - which is to Bjarke Freund-Hansen. Bjarke states that having several references of a singleton results in have several singletons. That is certainly not true since there are no deep-copies. – M. Mimpen Feb 17 '14 at 18:15
  • 7
    @M.Mimpen: I take his comment to refer more to the semantic effect. Once you outlaw calls to `getInstance()`, you've effectively tossed out the one useful difference between the Singleton pattern and an ordinary reference. As far as the rest of the code is concerned, singleness is no longer a property. Only the caller of `getInstance()` ever needs to know or even care how many instances there are. With only one caller, it costs more in effort and flexibility for the class to reliably enforce singleness than it does to have the caller simply store a reference and reuse it. – cHao Feb 17 '14 at 18:52
  • 2
    @cHao I don't really understand your concern. The singleton class will ensure there is only one copy of itself inside its implementation. The rest of the code shouldn't care about how many copies there are. The code just calls the singleton class that was passed to it right? – LegendLength Jan 06 '16 at 02:14
  • 1
    @LegendLength: It's about unwarranted dependencies. Code using a singleton either gets the instance itself (thereby tying itself to the singleton class for no good reason), or is passed the instance (thereby obviating the Singleton pattern -- without the global point of access, Singleton is inferior to just-create-one). And frankly, there is _almost never_ a reason for a class to enforce the singleness of its instance. – cHao Jan 06 '16 at 03:04
69

The singleton pattern is not a problem in itself. The problem is that the pattern is often used by people developing software with object-oriented tools without having a solid grasp of OO concepts. When singletons are introduced in this context they tend to grow into unmanageable classes that contain helper methods for every little use.

Singletons are also a problem from a testing perspective. They tend to make isolated unit-tests difficult to write. Inversion of control (IoC) and dependency injection are patterns meant to overcome this problem in an object-oriented manner that lends itself to unit testing.

In a garbage collected environment singletons can quickly become an issue with regard to memory management.

There is also the multi-threaded scenario where singletons can become a bottleneck as well as a synchronization issue.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Kimoz
  • 365
  • 4
  • 11
  • 6
    i know it is many year old thread. hi @Kimoz u said:- singletons can quickly become an issue with regard to memory management. would like to explain in more detail what kind of problem may arrive regarding singleton & garbage collection. – Thomas Apr 04 '14 at 14:09
  • @Kimoz, The question is asking *"Why is the singleton pattern not a problem in itself?"* and you have merely repeated the point but provided not even a single valid use case of the singleton pattern. – Pacerier Jun 25 '14 at 01:24
  • @Thomas, because a singleton by definition exists in only one instance. So, it's often complex to assign the only reference to null. It can be done, but it means that you fully control the point after which the singleton is not used in your app. And this is rare, and usually quite the opposite of what singleton enthusiast are looking for : a simple way to make a single instance *always* accessible. On some DI framworks like Guice or Dagger, it is not possible to get rid of a singleton and it stays forever in memory. (Though container provided singletons are far better than home made ones). – Snicolas May 28 '15 at 04:49
55

A singleton gets implemented using a static method. Static methods are avoided by people who do unit testing because they cannot be mocked or stubbed. Most people on this site are big proponents of unit testing. The generally most accepted convention to avoid them is using the inversion of control pattern.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
jwanagel
  • 4,008
  • 1
  • 22
  • 29
  • 9
    That does sound more like a problem with the unit testing that can test objects (units), functions (units), whole libraries (units), but fail with anything static in class (also units). – v010dya Feb 03 '14 at 04:35
  • 3
    aren't you suppose to moc all external references anyway? If you are, then what's a problem to moc singleton, if not, are you really doing unit testing? – Dainius Oct 24 '14 at 11:28
  • @Dainius: Mocking *instances* is a lot less trouble than mocking classes. You could conceivably extract the class under test from the rest of the application and test with a fake `Singleton` class. However, that immensely complicates the testing process. For one, now you need to be able to unload classes at will (not really an option in most languages), or start a new VM for each test (read: tests may take thousands of times as long). For two, though, the dependency on `Singleton` is an implementation detail that is now leaking all over your tests. – cHao Jan 11 '15 at 03:07
  • Powermock can mock static stuff. – Snicolas May 28 '15 at 04:50
  • does mocking an object mean creating real object? If mocking does not create a real object then why does it matter whether the class is singleton or method is static? – Arun Raaj Aug 13 '18 at 11:12
  • You can mock static class methods in most popular languages' mock libraries. But that doesn't mean you should use static methods everywhere :) – Juha Untinen Jul 26 '19 at 07:54
46

Singletons are also bad when it comes to clustering. Because then, you do not have "exactly one singleton" in your application anymore.

Consider the following situation: As a developer, you have to create a web application which accesses a database. To ensure that concurrent database calls do not conflict each other, you create a thread-save SingletonDao:

public class SingletonDao {
    // songleton's static variable and getInstance() method etc. omitted
    public void writeXYZ(...){
        synchronized(...){
            // some database writing operations...
        }
    }
}

So you are sure that only one singleton in your application exists and all database go through this one and only SingletonDao. Your production environment now looks like this: Single Singleton

Everything is fine so far.

Now, consider you want to set up multiple instances of your web application in a cluster. Now, you suddenly have something like this:

Many singletons

That sounds weird, but now you have many singletons in your application. And that is exactly what a singleton is not supposed to be: Having many objects of it. This is especially bad if you, as shown in this example, want to make synchronized calls to a database.

Of course this is an example of a bad usage of a singleton. But the message of this example is: You can not rely that there is exactly one instance of a singleton in your application - especially when it comes to clustering.

Uooo
  • 5,938
  • 7
  • 34
  • 62
  • 4
    if you don't know how to implement singleton, you shouldn't do that. If you don't know what you are doing, you should find that first, and only after that do what you need. – Dainius Oct 24 '14 at 11:30
  • 5
    This is interesting, I have a question. So what exactly is the problem if singletons - each on a different machine/JVM - are connecting to a single database? Singletons scope is only for that particular JVM, and that is still true even in a cluster. Rather than just philosophically saying that this particular situation is bad because our intent was a single object across application I would be happy to see any technical problems that can arise because of this arrangement. – Saurabh Patil Oct 20 '16 at 17:52
  • You describe solution for a problem that can be solved with db mechanism called Transaction. Frameworks like Spring used Singletons as default representation for beans and everyone is fine for years. You just picked wrong solution for your problem. – Mr Jedi Jul 09 '20 at 16:37
  • "ensure that concurrent database calls do not conflict each other" - isn't it the task of a database to manage concurrent access? ACID? I=Isolation? – Thomas Weller May 26 '21 at 16:38
43
  1. It is easily (ab)used as a global variable.
  2. Classes that depend on singletons are relatively harder to unit test in isolation.
asgs
  • 3,718
  • 6
  • 36
  • 49
jop
  • 77,529
  • 10
  • 52
  • 52
34

Monopoly is the devil and singletons with non-readonly/mutable state are the 'real' problem...

After reading Singletons are Pathological Liars as suggested in jason's answer I came across this little tidbit that provides the best presented example of how singletons are often misused.

Global is bad because:

  • a. It causes namespace conflict
  • b. It exposes the state in a unwarranted fashion

When it comes to Singletons

  • a. The explicit OO way of calling them, prevents the conflicts, so point a. is not an issue
  • b. Singletons without state are (like factories) are not a problem. Singletons with state can again fall in two categories, those which are immutable or write once and read many (config/property files). These are not bad. Mutable Singletons, which are kind of reference holders are the ones which you are speaking of.

In the last statement he's referring to the blog's concept of 'singletons are liars'.

How does this apply to Monopoly?

To start a game of monopoly, first:

  • we establish the rules first so everybody is on the same page
  • everybody is given an equal start at the beginning of the game
  • only one set of rules is presented to avoid confusion
  • the rules aren't allowed to change throughout the game

Now, for anybody who hasn't really played monopoly, these standards are ideal at best. A defeat in monopoly is hard to swallow because, monopoly is about money, if you lose you have to painstakingly watch the rest of the players finish the game, and losses are usually swift and crushing. So, the rules usually get twisted at some point to serve the self-interest of some of the players at the expense of the others.

So you're playing monopoly with friends Bob, Joe, and Ed. You're swiftly building your empire and consuming market share at an exponential rate. Your opponents are weakening and you start to smell blood (figuratively). Your buddy Bob put all of his money into gridlocking as many low-value properties as possible but his isn't receiving a high return on investment the way he expected. Bob, as a stroke of bad luck, lands on your Boardwalk and is excised from the game.

Now the game goes from friendly dice-rolling to serious business. Bob has been made the example of failure and Joe and Ed don't want to end up like 'that guy'. So, being the leading player you, all of a sudden, become the enemy. Joe and Ed start practicing under-the-table trades, behind-the-back money injections, undervalued house-swapping and generally anything to weaken you as a player until one of them rises to the top.

Then, instead of one of them winning, the process starts all over. All of a sudden, a finite set of rules becomes a moving target and the game degenerates into the type of social interactions that would make up the foundation of every high-rated reality TV show since Survivor. Why, because the rules are changing and there's no consensus on how/why/what they're supposed to represent, and more importantly, there's no one person making the decisions. Every player in the game, at that point, is making his/her own rules and chaos ensues until two of the players are too tired to keep up the charade and slowly give up.

So, if a rulebook for a game accurately represented a singleton, the monopoly rulebook would be an example of abuse.

How does this apply to programming?

Aside from all of the obvious thread-safety and synchronization issues that mutable singletons present... If you have one set of data, that is capable of being read/manipulated by multiple different sources concurrently and exists during the lifetime of the application execution, it's probably a good time to step back and ask "am I using the right type of data structure here".

Personally, I have seen a programmer abuse a singleton by using it as some sort of twisted cross-thread database store within an application. Having worked on the code directly, I can attest that it was a slow (because of all the thread locks needed to make it thread-safe) and a nightmare to work on (because of the unpredictable/intermittent nature of synchronization bugs), and nearly impossible to test under 'production' conditions. Sure, a system could have been developed using polling/signaling to overcome some of the performance issues but that wouldn't solve the issues with testing and, why bother when a 'real' database can already accomplish the same functionality in a much more robust/scalable manner.

A Singleton is only an option if you need what a singleton provides. A write-one read-only instance of an object. That same rule should cascade to the object's properties/members as well.

Community
  • 1
  • 1
Evan Plaice
  • 13,310
  • 4
  • 70
  • 94
  • 1
    What if singleton cashes some data? – Yola Dec 11 '14 at 06:54
  • @Yola It would cut down on the number of writes if the singleton was scheduled to update on a predetermined and/or fixed schedule, thereby reducing thread contention. Still, you wouldn't be able to accurately test any of the code interacting with the singleton unless you mock a non-singleton instance that simulates the same usage. The TDD folks would probably have a fit but it would work. – Evan Plaice Dec 15 '14 at 05:35
  • @EvanPlaice: Even with a mock, you'd have some issues with code that says `Singleton.getInstance()`. A language that supports reflection might be able to work around that by setting the field where the One True Instance is stored. IMO, though, tests become a bit less trustworthy once you've taken to monkeying around with another class's private state. – cHao Jan 09 '15 at 17:39
32

Singleton is not about single instance!

Unlike other answers I don't want to talk about what is wrong with Singletons but to show you how powerful and awesome they are when used right!

  • Problem: Singleton can be a challenge in multi-threading environment
    Solution: Use a single threaded bootstrap process to initialize all the dependencies of your singleton.
  • Problem: It is hard to mock singletons.
    Solution: Use method Factory pattern for mocking

You can map MyModel to TestMyModel class that inherits it, everywhere when MyModel will be injected you will get TestMyModel instread. - Problem: Singletons can cause memory leaks as they never disposed.
Solution: Well, dispose them! Implement a callback in your app to properly dispose a singletons, you should remove any data linked to them and finally: remove them from the Factory.

As I stated at the title singleton are not about single instance.

  • Singletons improves readability: You can look at your class and see what singleton it injected to figure out what is it's dependencies.
  • Singletons improves maintenance: Once you removed a dependency from a class you just deleted some singleton injection, you don't need to go and edit a big link of other classes that just moved your dependency around(This is smelly code for me @Jim Burger)
  • Singletons improves memory and performance: When some thing happens in your application, and it takes a long chain of callbacks to deliver, you are wasting memory and performance, by using Singleton you are cutting the middle man, and improve your performance and memory usage(by avoiding unnecessary local variables allocations).
Llama
  • 25,925
  • 5
  • 49
  • 68
Ilya Gazman
  • 27,805
  • 19
  • 119
  • 190
  • 2
    This doesn't address my main issue with Singletons which is they allow access to global state from any of the thousands of classes in your project. – LegendLength Jan 06 '16 at 02:39
  • 9
    That would be the purpose... – Ilya Gazman Jan 06 '16 at 05:19
  • LegendLength Why is that wrong? For example, in my application I have a singleton `Settings` object which is accessible from any widget so that each widget knows about how to format displayed numbers. If it was not a globally accessible object I would have to inject it in constructor to each and every widget in the constructor and keep the reference to it as a member variable. This is a terrible waste of memory and time. – V.K. Aug 21 '19 at 11:00
24

See Wikipedia Singleton_pattern

It is also considered an anti-pattern by some people, who feel that it is overly used, introducing unnecessary limitations in situations where a sole instance of a class is not actually required.[1][2][3][4]

References (only relevant references from the article)

  1. ^ Alex Miller. Patterns I hate #1: Singleton, July 2007
  2. ^ Scott Densmore. Why singletons are evil, May 2004
  3. ^ Steve Yegge. Singletons considered stupid, September 2004
  4. ^ J.B. Rainsberger, IBM. Use your singletons wisely, July 2001
user2418306
  • 2,173
  • 1
  • 19
  • 29
GUI Junkie
  • 509
  • 1
  • 14
  • 27
  • 9
    A description about the pattern doesn't explain why it is considered as evil... – Jrgns Sep 26 '08 at 09:31
  • 2
    Hardly fair: "It is also considered an anti-pattern by some people, who feel that it is overly used, introducing unnecessary limitations in situations where a sole instance of a class is not actually required." Look at the references... Anyway there’s RTFM to me. – GUI Junkie Sep 26 '08 at 10:58
23

My answer on how Singletons are bad is always, "they are hard to do right". Many of the foundational components of languages are singletons (classes, functions, namespaces and even operators), as are components in other aspects of computing (localhost, default route, virtual filesystem, etc.), and it is not by accident. While they cause trouble and frustration from time to time, they also can make a lot of things work a LOT better.

The two biggest screw ups I see are: treating it like a global & failing to define the Singleton closure.

Everyone talks about Singleton's as globals, because they basically are. However, much (sadly, not all) of the badness in a global comes not intrinsically from being global, but how you use it. Same goes for Singletons. Actually more so as "single instance" really doesn't need to mean "globally accessible". It is more a natural byproduct, and given all the bad that we know comes from it, we shouldn't be in such a hurry to exploit global accessibility. Once programmers see a Singleton they seem to always access it directly through its instance method. Instead, you should navigate to it just like you would any other object. Most code shouldn't even be aware it is dealing with a Singleton (loose coupling, right?). If only a small bit of code accesses the object like it is a global, a lot of harm is undone. I recommend enforcing it by restricting access to the instance function.

The Singleton context is also really important. The defining characteristic of a Singleton is that there is "only one", but the truth is it is "only one" within some kind of context/namespace. They are usually one of: one per thread, process, IP address or cluster, but can also be one per processor, machine, language namespace/class loader/whatever, subnet, Internet, etc.

The other, less common, mistake is to ignore the Singleton lifestyle. Just because there is only one doesn't mean a Singleton is some omnipotent "always was and always will be", nor is it generally desirable (objects without a begin and end violate all kinds of useful assumptions in code, and should be employed only in the most desperate of circumstances.

If you avoid those mistakes, Singletons can still be a PITA, bit it is ready to see a lot of the worst problems are significantly mitigated. Imagine a Java Singleton, that is explicitly defined as once per classloader (which means it needs a thread safety policy), with defined creation and destruction methods and a life cycle that dictates when and how they get invoked, and whose "instance" method has package protection so it is generally accessed through other, non-global objects. Still a potential source of trouble, but certainly much less trouble.

Sadly, rather than teaching good examples of how to do Singletons. We teach bad examples, let programmers run off using them for a while, and then tell them they are a bad design pattern.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Christopher Smith
  • 4,947
  • 1
  • 30
  • 18
17

It's not that singletons themselves are bad but the GoF design pattern is. The only really argument that is valid is that the GoF design pattern doesn't lend itself in regards to testing, especially if tests are run in parallel.

Using a single instance of an class is a valid construct as long as you apply the following means in code:

  1. Make sure the class that will be used as a singleton implements an interface. This allows stubs or mocks to be implemented using the same interface

  2. Make sure that the Singleton is thread-safe. That's a given.

  3. The singleton should be simple in nature and not overly complicated.

  4. During the runtime of you application, where singletons need to be passed to a given object, use a class factory that builds that object and have the class factory pass the singleton instance to the class that needs it.

  5. During testing and to ensure deterministic behavior, create the singleton class as separate instance as either the actual class itself or a stub/mock that implements its behavior and pass it as is to the class that requires it. Don't use the class factor that creates that object under test that needs the singleton during test as it will pass the single global instance of it, which defeats the purpose.

We've used Singletons in our solutions with a great deal of success that are testable ensuring deterministic behavior in parallel test run streams.

Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842
16

Vince Huston has these criteria, which seem reasonable to me:

Singleton should be considered only if all three of the following criteria are satisfied:

  • Ownership of the single instance cannot be reasonably assigned
  • Lazy initialization is desirable
  • Global access is not otherwise provided for

If ownership of the single instance, when and how initialization occurs, and global access are not issues, Singleton is not sufficiently interesting.

js.
  • 1,575
  • 16
  • 20
16

I'd like to address the 4 points in the accepted answer, hopefully someone can explain why I'm wrong.

  1. Why is hiding dependencies in your code bad? There are already dozens of hidden dependencies (C runtime calls, OS API calls, global function calls), and singleton dependencies are easy to find (search for instance()).

    "Making something global to avoid passing it around is a code smell." Why isn't passing something around to avoid making it a singleton a code smell?

    If you're passing an object through 10 functions in a call stack just to avoid a singleton, is that so great?

  2. Single Responsibility Principle: I think this is a bit vague and depends on your definition of responsibility. A relevant question would be, why does adding this specific "responsibility" to a class matter?

  3. Why does passing an object to a class make it more tightly coupled than using that object as a singleton from within the class?

  4. Why does it change how long the state lasts? Singletons can be created or destroyed manually, so the control is still there, and you can make the lifetime the same as a non-singleton object's lifetime would be.

Regarding unit tests:

  • not all classes need to be unit tested
  • not all classes that need to be unit tested need to change the implementation of the singleton
  • if they do need be unit tested and do need to change the implementation, it's easy to change a class from using a singleton to having the singleton passed to it via dependency injection.
Jon
  • 5,025
  • 4
  • 35
  • 48
  • 1
    1. All those hidden dependencies? *Those are bad too.* Hidden dependencies are always evil. But in the case of the CRT and OS, they're already there, and they're the only way to get something done. (Try writing a C program without using the runtime or OS.) That ability to do stuff vastly outweighs their negatives. Singletons in our code don't get that luxury; since they're firmly within our sphere of control and responsibility, every usage (read: every additional hidden dependency) should be justifiable as the only reasonable way to get stuff done. Very, *very* few of them actually are. – cHao Feb 12 '13 at 14:17
  • 2. "Responsibility" is typically defined as "reason to change". A singleton ends up both managing its lifetime and doing its real job. If you change how the job is done *or* how the object graph is built, you have to change the class. But if you have other code build the object graph, and your class just does its real job, that initialization code can set up the object graph however it likes. Everything's much more modular and testable, because you can insert test doubles and tear everything down at will, and you're no longer relying on hidden moving parts. – cHao Feb 12 '13 at 14:39
  • 3. *It doesn't have to. That's the point.* Tight coupling is a bad thing. Consider: If you pass an object of type A in via the constructor or whatever, then the object can use it when it has to do A'ish things. But that object could also be of type B, which inherits from A. And as long as B *properly* extends A (read: follows LSP), then the object can still do all its A'ish things without having to even think about the extra spiff that that B is doing. But if you say `A.getInstance()`, suddenly either you can *only* have an A, or A has to do some contortions to allow `getInstance` to work. – cHao Feb 12 '13 at 14:47
  • 4. Capital-S "Singletons" cannot be created or destroyed manually. The whole point is that there can be only one instance, which semantically lasts for the whole life of the application (though it's often only initialized when first requested). If you have single instances of stuff, that's not quite as big a deal...but you no longer have a Singleton. And you still have those hidden moving parts, unless you're passing those single instances to the constructors of objects that want to use them. – cHao Feb 12 '13 at 15:08
  • Regarding unit tests: • All classes *should* be unit tested. Otherwise, you can't point at a particular block of code and say "the problem's in there". • All classes that need to be unit tested simply *aren't testable* if they tie themselves to mutable global state. • If you're properly testing all classes, and they're all therefore getting their instance via DI...that singleton *no longer needs to be a singleton*. You've removed any need for the global access point, and the object doesn't care how many instances there are. – cHao Feb 12 '13 at 15:15
  • 1
    @cHao: 1. It's good that you recognize that the "ability to do stuff vastly outweighs their negatives." An example would be a logging framework. It's evil to mandate passing a global logging object by dependency injection through layers of function calls if it means that developers are discouraged from logging. Hence, singleton. 3. Your tight coupling point is only relevant if you want clients of the class to control behavior via polymorphism. That's often not the case. – Jon Feb 13 '13 at 22:48
  • 2
    4. I'm not sure that "cannot be destroyed manually" is a logical implication of "can be only one instance". If that's how you define singleton, then we're not talking about the same thing. All classes _should not_ be unit tested. That's a business decision, and sometimes time-to-market or development cost will take precedence. – Jon Feb 13 '13 at 22:48
  • 1. It's evil to mandate passing *anything* through a bunch of layers. Each object should only take the stuff it needs to do its job. This doesn't mean passing a logger to the stuff you create; it means *not creating that stuff*. I might almost support a singleton for logging, as potentially *everything* could use it and its operation doesn't actually affect the program. But for objects with meaningful state, they suck. If you have, say, a Customer class that owns an Account, Customer's constructor shouldn't take the stuff it needs to create the account; it should take *an Account*. – cHao Feb 13 '13 at 23:47
  • 1
    3. If you don't want polymorphism, then you don't even need an instance. You might as well make it a static class, cause you're tying yourself to a single object and a single implementation anyway -- and at least then the API isn't lying to you as much. – cHao Feb 13 '13 at 23:50
  • 4. I am talking about the GoF-blessed, capital-S "Singleton pattern". The one that includes a non-public constructor and a public `getInstance()` method. The one that mandates that only one instance ever exist. It manages the One True Instance, and prohibits the existence of a second one -- and keeps others from overriding its oneness by creating another instance (and hopefully from destroying the OTI). If you're not talking about that, you're just talking about a global variable or service locator. – cHao Feb 13 '13 at 23:54
  • *All classes should be unit tested.* To skip testing anything is half-assing it for time's sake. There are of course plenty of times when (half-assed and faster) > (thorough and slower)...but make no mistake, that doesn't reduce the importance of testing everything. Whoever's in charge has just decided that time-to-market is more important than reliability. – cHao Feb 14 '13 at 00:22
  • For the case of logging I prefer to have a logging object that sits in the 'main' class. If any other classes need to log they should throw an exception or somehow send the error up to the main class. Then the main class does all the logging. – LegendLength Jan 06 '16 at 02:25
14

Singletons are bad from a purist point of view.

From a pratical point of view, a singleton is a trade-off developing time vs complexity.

If you know your application won't change that much they are pretty OK to go with. Just know that you may need to refactor things up if your requirements change in an unexpected way (which is pretty OK in most cases).

Singletons sometimes also complicate unit testing.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
tacone
  • 10,962
  • 8
  • 39
  • 59
  • 3
    My experience is that *starting* with singletons will really hurt you even in the short run, not counting the long run. This effect might me less so if the application is already existing for some time, and probably already infested with other singletons. Starting from scratch? Avoid them at all costs! Want a single instance of an object? Let a factory manage the instantiation of this object. – Sven May 17 '13 at 19:36
  • 1
    AFAIK Singleton *is* a factory method. Thus I don't get your recommendation. – tacone May 17 '13 at 22:37
  • 3
    "A factory" != "A factory_method that cannot be separated from the other useful stuff in the same class" – Sven May 18 '13 at 00:12
13

There is nothing inherently wrong with the pattern, assuming it is being used for some aspect of your model which is truly single.

I believe the backlash is due to its overuse which, in turn, is due to the fact that it's the easiest pattern to understand and implement.

Ben Hoffstein
  • 98,117
  • 8
  • 99
  • 119
13

I'm not going to comment on the good/evil argument, but I haven't used them since Spring came along. Using dependency injection has pretty much removed my requirements for singleton, servicelocators and factories. I find this a much more productive and clean environment, at least for the type of work I do (Java-based web applications).

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
prule
  • 2,408
  • 31
  • 28
  • 3
    aren't Spring beans, by default, Singletons? – slim Feb 08 '10 at 15:50
  • 3
    Yeah, but I mean 'coding' singletons. I haven't 'written a singleton' (i.e. with a private constructor yada yada yada as per design pattern) - but yes, with spring I am using a single instance. – prule Feb 16 '10 at 19:59
  • 4
    so when others do it, it's Ok (if I will use that after), but if others do it and I will not use it, it's evil? – Dainius Oct 24 '14 at 11:32
11

Singleton is a pattern and can be used or abused just like any other tool.

The bad part of a singleton is generally the user (or should I say the inappropriate use of a singleton for things it is not designed to do). The biggest offender is using a singleton as a fake global variable.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Martin York
  • 234,851
  • 74
  • 306
  • 532
  • 1
    Thanks Loki :) Exactly my point. The whole witch hunt reminds me of the goto debate. Tools are for people who know how to use them; using a tool you don't like may be dangerous for you so avoid it but DON'T tell others not to use / not to learn to use it properly. I'm not exactly "pro-singleton" but I like the fact that I have tool like that and I can feel where it is appropriate to use it. Period. – dkellner Dec 29 '15 at 16:58
9

When you write code using singletons, say, a logger or a database connection, and afterwards you discover you need more than one log or more than one database, you’re in trouble.

Singletons make it very hard to move from them to regular objects.

Also, it’s too easy to write a non-thread-safe singleton.

Rather than using singletons, you should pass all the needed utility objects from function to function. That can be simplified if you wrap all them into a helper object, like this:

void some_class::some_function(parameters, service_provider& srv)
{
    srv.get<error_logger>().log("Hi there!");
    this->another_function(some_other_parameters, srv);
}
Roman Odaisky
  • 2,375
  • 19
  • 24
  • 4
    passing argument for every method is brilliant, it should go to at least top 10 ways how to pollute your api. – Dainius Oct 24 '14 at 11:34
  • That’s an obvious drawback, and one that should have been handled by the language, by means of arguments that somehow propagate into nested calls, but absent such support, it has to be done manually. Consider that even natural singletons, like an object representing the system clock, have potential for trouble. For example, how are you going to cover clock-dependent code (think multiple tariff electricity meter) with tests? – Roman Odaisky Oct 26 '14 at 13:23
  • depends what you are testing, if you aren't testing singleton, why you care how it behaves, if your 2 remote object depends on each other behavior, it's not singleton problem.. – Dainius Oct 27 '14 at 16:32
  • Could you provide which language would propagation into nested calls? – Dainius Oct 27 '14 at 16:33
  • Lisp dynamic variables are something similar. As for testing, let me clarify. Suppose you have a singleton object that returns, say, the current date/time. You have datetime-dependent code that you need to test by providing mock datetime values to certain functions. That’s not easily achievable unless you have something like a datetime provider that you can replace with a mock version for particular calls. – Roman Odaisky Oct 28 '14 at 17:18
  • 1
    If you have one module that depends on another and you don't know /can't moc it, you will have hard irregardless of is it singleton or not. People are using inheritance way to often, where they should use composition, but you don't say that inheritance are bad, and OOP should be avoid at all costs, because so many people are doing design mistakes there, or are you? – Dainius Oct 29 '14 at 13:50
  • @Dainius But you don't pass it to every method. You only pass it to methods & classes that need it. Would you prefer to hide the fact that a class needs to access some other object? Should we make CustomerList global so we don't have to pass it around to other classes all the time? – LegendLength Jan 06 '16 at 02:28
  • @LegendLength but you have class members and don't pass them to every class methods, because you want to know, which method needs them, or do you? And singleton isn't global variable. – Dainius Jan 07 '16 at 07:45
  • Classes should be small enough that 'global' access to members within the class are no problem. But for a program with 500 classes it's difficult when any of those classes are accessing a singleton directly. I don't have any issue with singletons that are non-global. I'm only talking about the common case where they are accessed globally: MyConfiguration.getUsername() . – LegendLength Jan 07 '16 at 09:38
8

Recent article on this subject by Chris Reath at Coding Without Comments.

Note: Coding Without Comments is no longer valid. However, The article being linked to has been cloned by another user.

http://geekswithblogs.net/AngelEyes/archive/2013/09/08/singleton-i-love-you-but-youre-bringing-me-down-re-uploaded.aspx

stephenbayer
  • 11,718
  • 15
  • 59
  • 98
David
  • 13,789
  • 24
  • 77
  • 99
8

The problems with singletons is the issue of increased scope and therefore coupling. There is no denying that there are some of situations where you do need access to a single instance, and it can be accomplished other ways.

I now prefer to design around an inversion of control (IoC) container and allow the the lifetimes to be controlled by the container. This gives you the benefit of the classes that depend on the instance to be unaware of the fact that there is a single instance. The lifetime of the singleton can be changed in the future. Once such example I encountered recently was an easy adjustment from single threaded to multi-threaded.

FWIW, if it a PIA when you try to unit test it then it's going to PIA when you try to debug, bug fix or enhance it.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Mark Lindell
  • 833
  • 8
  • 18
7

Too many people put objects which are not thread safe in a singleton pattern. I've seen examples of a DataContext (LINQ to SQL) done in a singleton pattern, despite the fact that the DataContext is not thread safe and is purely a unit-of-work object.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Aaron Powell
  • 24,268
  • 14
  • 93
  • 147
  • many people write unsafe multi-threaded code, does that mean we should eliminate threads? – Dainius Oct 24 '14 at 11:35
  • @Dainius: In fact, yes. IMO the default concurrency model should be multi-process, with a way for two processes to (1) pass messages to each other easily, and/or (2) share memory on an as-needed basis. Threading is useful if you want to share *everything*, but you never really want that. It could be emulated by sharing the whole address space, but that would also be considered an anti-pattern. – cHao Jan 09 '15 at 18:20
  • @Dainius: And of course, that's assuming that honest-to-goodness concurrency is needed at all. Often all you want is to be able to do one thing while you wait for the OS to do something else. (Updating the UI while reading from a socket, for example.) A decent async API could make full-on threading unnecessary in a huge majority of cases. – cHao Jan 09 '15 at 18:50
  • so if you have huge matrix of data, that you need process, it's better to do that in single thread, because to many people might do that wrong.. – Dainius Jan 10 '15 at 19:19
  • @Dainius: In many cases, yes. (Threading could actually *slow you down*, if you add synchronization to the mix. This is a prime example of why multithreading shouldn't be most people's first thought.) In other cases, it'd be better to have two processes that share just the needed stuff. Of course, you'd have to arrange for the processes to share memory. But frankly, i see that as a *good* thing -- far better, at least, than defaulting to share-everything mode. It requires you to explicitly say (and so, ideally, to know) which parts are shared, and thus which parts need to be thread-safe. – cHao Jan 10 '15 at 23:49
7

Singletons are NOT bad. It's only bad when you make something globally unique that isn't globally unique.

However, there are "application scope services" (think about a messaging system that makes components interact) - this CALLS for a singleton, a "MessageQueue" - class that has a method "SendMessage(...)".

You can then do the following from all over the place:

MessageQueue.Current.SendMessage(new MailArrivedMessage(...));

And, of course, do:

MessageQueue.Current.RegisterReceiver(this);

in classes that implement IMessageReceiver.

  • 6
    And if I want to create a second message queue, with a smaller scope, why shouldn't I be allowed to reuse your code to create it? A singleton prevents that. But if you'd just created a regular message queue class, and then created one global instance to act as the "application scope" one, I could create a second instance for other use. But if you make the class a singleton, I'd have to write a *second* message queue class. – jalf Nov 10 '10 at 14:39
  • 1
    Also why shouldn't we just have a global CustomerOrderList so we can call it nicely from anywhere like MessageQueue? I believe the answer is the same for both: It's effectively making a global variable. – LegendLength Jan 06 '16 at 02:32
6

Here is one more thing about singletons which nobody said yet.

In most cases "singletonity" is a detail of implementation for some class rather than characteristic of its interface. Inversion of Control Container may hide this characteristic from class users; you just need to mark your class as a singleton (with @Singleton annotation in Java for example) and that's it; IoCC will do the rest. You don't need to provide global access to your singleton instance because the access is already managed by IoCC. Thus there is nothing wrong with IoC Singletons.

GoF Singletons in opposite to IoC Singletons are supposed to expose "singletonity" in the interface through getInstance() method, and so that they suffer from everything said above.

Volodymyr Frolov
  • 1,174
  • 4
  • 14
  • 24
  • 3
    In my opinion, "singletonity" is a run-time environment detail, and should not be considered by the programmer that wrote the class code. Rather, it is a consideration to be made by the class USER. only the USER knows how many instances are actually required. – Earth Engine Apr 12 '13 at 04:50
5

Singletons aren't evil, if you use it properly & minimally. There are lot of other good design patterns which replaces the needs of singleton at some point (& also gives best results). But some programmers are unaware of those good patterns & uses the singleton for all the cases which makes the singleton evil for them.

Sri
  • 3,978
  • 1
  • 33
  • 38
  • 1
    Awesome! Completely agree! But you could, and maybe should, elaborate much more. Such as expanding which design patterns are most commonly ignored and how to "properly and minimally" use singletons. Easier said than [done](http://programmers.stackexchange.com/a/218322/4261)! :P – cregox Nov 16 '13 at 10:11
  • Basically the alternative is to pass objects around via method parameters, rather than accessing them via global state. – LegendLength Jan 06 '16 at 02:37
5

Firstly a class and its collaborators should firstly perform their intended purpose rather than focusing on dependents. Lifecycle management (when instances are created and when they go out of scope) should not be part of the classes responsibility. The accepted best practice for this is to craft or configure a new component to manage dependencies using dependency injection.

Often software gets more complicated it makes sense to have multiple independent instances of the Singleton class with different state. Committing code to simply grab the singleton is wrong in such cases. Using Singleton.getInstance() might be ok for small simple systems but it doesn't work/scale when one might need a different instance of the same class.

No class should be thought of as a singleton but rather that should be an application of it's usage or how it is used to configure dependents. For a quick and nasty this does not matter - just luke hard coding say file paths does not matter but for bigger applications such dependencies need to be factored out and managed in more appropriate way using DI.

The problems that singleton cause in testing is a symptom of their hard coded single usage case/environment. The test suite and the many tests are each individual and separate something that is not compatible with hard coding a singleton.

Reeta Wani
  • 197
  • 4
  • 13
mP.
  • 17,011
  • 10
  • 66
  • 101
4

Because they are basically object oriented global variables, you can usually design your classes in such a way so that you don't need them.

Ycros
  • 1,660
  • 2
  • 14
  • 10
  • If you class isn't limited to once instance, you'll need static members in your class managed by semaphores which comes out to pretty much the same thing! What is your proposed alternative? – Jeach Feb 18 '10 at 15:21
  • I have a huge application with a "MainScreen" this screen opens up many smaller modal/non modal windows/ UI forms. IMHO I feel that the MainScreen should be a singleton so that for example, a widget somewhere in a far corner of the application wants to show its status in the MainScreen's status bar, all it has to do is MainScreen.getInstance().setStatus("Some Text"); What do you propose as an alternative ? Pass MainScreen all over the application ?? :D – Salvin Francis Apr 06 '10 at 08:59
  • 2
    @SalvinFrancis: What i'd recommend is, you stop having objects that care about stuff they shouldn't care about and sneak across the app to mess around with each other. :) Your example would much better done with events. When you do events correctly, a widget doesn't even have to care whether there's a MainScreen at all; it just broadcasts "hey, stuff happened", and *whatever* has subscribed to the "stuff happened" event (be it a MainScreen, a WidgetTest, or something else entirely!) decides how it wants to respond. That's how OOP is *supposed* to be done anyway. :) – cHao Feb 26 '13 at 21:48
  • 1
    @Salvin Consider how hard it is to reason about MainScreen when debugging if it is being 'silently' updated by many components. Your example is a perfect reason why singletons are bad. – LegendLength Jan 06 '16 at 02:35
4

A pattern emerges when several people (or teams) arrives at similar or identical solutions. A lot of people still use singletons in their original form or using factory templates (good discussion in Alexandrescu's Modern C++ Design). Concurrency and difficulty in managing the lifetime of the object are the main obstacles, with the former easily managed as you suggest.

Like all choices, Singleton has its fair share of ups and downs. I think they can be used in moderation, especially for objects that survive the application life span. The fact that they resemble (and probably are) globals have presumably set off the purists.

user22044
  • 216
  • 1
  • 3
3

This is what I think is missing from the answers so far:

If you need one instance of this object per process address space (and you are as confident as you can be that this requirement will not change), you should make it a singleton.

Otherwise, it's not a singleton.

This is a very odd requirement, hardly ever of interest to the user. Processes and address space isolation are an implementation detail. They only impact on the user when they want to stop your application using kill or Task Manager.

Apart from building a caching system, there aren't that many reasons why you'd be so certain that there should only be on instance of something per process. How about a logging system? Might be better for that to be per-thread or more fine-grained so you can trace the origin of messages more automatically. How about the application's main window? It depends; maybe you'll want all the user's documents to be managed by the same process for some reason, in which case there would be multiple "main windows" in that process.

Daniel Earwicker
  • 108,589
  • 35
  • 194
  • 274
3

The Singleton – the anti-pattern! by Mark Radford (Overload Journal #57 – Oct 2003) is a good read about why Singleton is regarded an anti-pattern. The article also discusses two alternatives design approaches for replacing Singleton.

Keith Pinson
  • 7,162
  • 5
  • 54
  • 97
Frank Grimm
  • 1,143
  • 7
  • 11
3

Some counterpoints from the author:

You are stuck if you need to make the class not single in the future Not at all - I was in this situation with a single database connection singleton that I wanted to turn into a connection pool. Remember that every singleton is accessed through a standard method:

MyClass.instance

This is similar to the signature of a factory method. All I did was update the instance method to return the next connection from the pool - no other changes required. That would have been far harder if we had NOT been using a singleton.

Singletons are just fancy globals Can't argue with that but so are all static fields and methods - anything that is accessed from the class rather than an instance is essentially global and I dont see so much pushback on the use of static fields?

Not saying that Singletons are good, just pushing back at some of the 'conventional wisdom' here.

Ewan Makepeace
  • 5,248
  • 8
  • 29
  • 31
  • 2
    no, you're missing the point. In the first point, I still don't have the option to *create another instance*. I can wish and hope and pray that the next time I call `getInstance()`, it'll give me a different instance, but I still have no way to just say "I've got one instance. Now I need a second instance for another task". On the second point, many things are just fancy globals, yes, but singletons couple this with a lot of unwanted baggage (the 1-instance restriction, the complex and error-prone synchronization issues), for example. – jalf Nov 10 '10 at 14:34
  • 1
    @Ewan: *Mutable* static fields are evil, for many of the reasons that Singletons are. If you haven't seen the pushback against them, you haven't been looking hard enough; `static` is just the C#/Java spelling for "global". :) As for static functions, they're a bit less of an issue without static variables; the biggest problem with globalness is the "action at a distance" and hidden dependencies that it brings about, and a function that has no inter-call storage space (no instance, and no mutable static variables) ends up quite limited in what it can depend on (and what it can mangle). – cHao Feb 13 '13 at 15:58
  • 1
    "Not at all - I was in this situation with a single database connection singleton that I wanted to turn into a connection pool." You still wanted this one class to be single. It changed from single connection to single connection pool. You would be screwed if you wanted to split your database server into two independent. Now your connection pool would need to know to which server to connect. Without singletons in the first place, the only change in your DIC would be to create a second DB connection object with the second servers details and inject it into all objects that moved to this DB. – Sven May 17 '13 at 19:52
2

It blurs the separation of concerns.

Supposed that you have a singleton, you can call this instance from anywhere inside your class. Your class is no longer as pure as it should be. Your class will now no longer operate on its members and the members that it receives explicitly. This will create confusion, because the users of the class don't know what is the sufficient information the class needs. The whole idea of encapsulation is to hide the how of a method from the users, but if a singleton is used inside the method, one will have to know the state of the singleton in order to use the method correctly. This is anti-OOP.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Graviton
  • 76,900
  • 138
  • 399
  • 575
  • 5
    Not quite sure about this answer. The same could be said for any object really. The real problem is that a Singleton can be accessed from ANYWHERE. A clean API and sufficient documentation can keep clients from using it incorrectly. – Outlaw Programmer Sep 26 '08 at 17:32
1

Off the top of my head:

  1. They enforce tight-coupling. If your singleton resides on a different assembly than its user, the using assembly cannot ever function without the assembly containing the singleton.
  2. They allow for circular dependencies, e.g., Assembly A can have a singleton with a dependency on Assembly B, and Assembly B can use Assembly A's singleton. All without breaking the compiler.
Jon Limjap
  • 89,838
  • 14
  • 96
  • 150