Funny how some subjects seem to attract catchy titles like flies. A lot of very clever people have written volumes about “The Simpleton Pattern”, and “Singletonitis” (bah, dead link, let’s use this instead then).
Many people are in love with the Singleton pattern. Others — a small minority, I suspect — consider it a mistake, an anti-pattern, or something that was only ever included in the Design Patterns book as a lifeline to procedural programmers who couldn’t really figure out this OOP thing.
I won’t pretend to be half as clever as all the people who have already written about the problems with singletons years ago, and I don’t think I have anything new to bring to the table. But it is a pattern I learned to loathe years ago. (Singletons do sound attractive when you first hear of them. But they pale a bit when you end up having to tear up and rewrite half your code just because all your singleton classes start revealing their shortcomings) And for a long time now, I’ve tried to convince other programmers that Singletons have some serious problems. Recently, it seems like I’m even getting noticed for it among the users of StackOverflow.
First, oneuser posts an answer to one question, and I comment with a mild disagreement, and the discussion goes on for a few more comments. As singleton rants go, this one is pretty mild, and I don’t really think about it any further. Then, a few weeks later, I discover his blog and this post. Wow! A convert. A person I know to be a smart and a knowledgeable programmer has changed his mind in response to something I said… I’m flattered.
And today, I noticed another question being posted, which had both Boost and Singletons in the title — how could I resist? Two subjects I enjoy talking about, even if the things I say about them are very different. Surprisingly, the comments there already mentioned me, and some of my earlier answers regarding singletons. Should I be flattered or worried that people have started bringing my name up when discussing Singletons?
Anyway, one of the comments also suggested I write a blog post describing my argument in detail. So I will. I’ll even throw in a redirect link from http://jalf.dk/singleton, to make it as easy as possible to find.
Two wrongs don’t make a right
There are a lot of problems with singletons. In fact, it’s surprising that so many people still consider the pattern useful, when it is afflicted with so many weaknesses and flaws. However, for now I will single out the two that I feel are the most fundamental: not just problems with how a singleton works, but with what they’re trying to achieve:
A singleton, as defined by the Gang of Four, combines two properties:
- it guarantees that exactly one instance of an object exists. While that one instance is typically created lazily, so it doesn’t technically exist throughout the entire application’s lifetime, it always seems to the programmer as if precisely one instance exists, and
- it guarantees global access to this one instance.
Let’s pick those apart a bit. The last one is easiest: it is, by now, fairly common knowledge that global state is bad. We don’t like global variables, we don’t like static class members, we don’t like anything that makes it harder to isolate bits of our code. Dependence on global state causes a lot of problems: it hurts parallelism, as access to global mutable state generally has to be serialized through the use of locks. It makes dependencies harder to detect and control (any function might silently decide to access our singleton. The function signature says nothing about this, so we have to read the source code of the function to determine if this is the case. And because it is so convenient to always just add a reference to a singleton, we tend to do it a lot. When you have a singleton, you quickly end up in a situation where three out of four classes depend on it. How did that happen? Why, logically speaking, do so many classes need direct access to the database? Or the renderer? Is that good design? Not only is this messy, it’s also painfully hard to fix after the fact. Once we have these dependencies on global objects everywhere, that’s a lot of code we need to change to eliminate the global. Almost every class will be impacted by the change, and a huge number of functions have to have their signatures modified to take that extra parameter replacing the global. Or even worse, the function has to be completely rewritten to eliminate the need for whatever service the singleton provided. The more globals you have in your project, the more your dependency graph starts resembling spaghetti. And the harder it gets to clean it up.
It hurts reusability, as code taken from one project and inserted into another may break because it depended on globals not present in the new project. It hurts testability partly for the same reason, a unit test testing a class must suddenly provide a number of globals as well just for the code under test to compile, but also because global state makes tests less deterministic. One test might change the state of this global, affecting the outcome of the next test to run.
Globals are bad for a lot of reasons. They have their uses, no doubt about that, but we should be suspicious whenever the solution to a problem involves global data. It might be the best solution, but often, it is more trouble than it’s worth.
The other point is more subtle. Why do I object to a class enforcing that “only one instance may exist”? It’s really just common sense. As the Agile movement tells us, we don’t really know what our code is going to look like tomorrow. Over the course of development, we have to adapt to changes, modify our code, revise decisions already made. Why put roadblocks in front of us? Why make it harder to adapt to unforeseen changes or requirements?
Today, I might think that I need only one logger instance. But what if I realize tomorrow that I need two? That’s not so far fetched. We may have one log we write ad-hoc messages intended for debugging purposes, solely to be read by developers, and another formalized log, where structured messages are written when predetermined events occur, so that the application can be monitored in production. Sure, we could define the two as completely separate classes, and then we’d only need one instance of each (but then we’d start duplicating code). Or we could use the same log instance to write to both logs (but then the logging code would become more complex, having to interleave two separate and non-overlapping logs.
Once we’ve accepted that an application may need more than one logger, shouldn’t we do ourselves the favor of ensuring that our loggers can be instantiated more than once, just in case it turns out to be the right thing to do? We’re not even adding any complexity, there’s no cost associated with this. On the contrary, we’re removing significant complexity. Thread-safe singletons are surprisingly hard to get right. Dependencies between singletons are tricky and circular ones can cause them to blow up in all sorts of fun ways. And let’s not even get into how to handle anything our singletons might do while the application is shutting down. What if the database singleton tries to write a simple “goodbye” log message to the log singleton? What if the log singleton got destroyed before the database one? Ouch.
Singletons are hard to write and hard to use. Removing them only simplifies our code, so if it also enables us to better adapt to unforeseen requirements, why shouldn’t we remove them?
Not convinced? Let’s think of some other examples then:
- the application configuration should be a singleton, right? We obviously can’t have more than one of those! Wrong. We can. We often do. Think about what happens when the user opens the “Options” screen and modifies the settings. During that time, two sets of settings exist: the “applied” settings that are currently in effect, and the “speculative” ones, currently being picked out by the user. Once he clicks OK, the speculative changes should be applied, replacing the ones that were previously in effect. But until then, we have two sets of settings to maintain.
- a database connection pool then! If we have more than one pool of connections, we can’t efficiently share them! Correct, but perhaps we don’t want to share them. Perhaps I want to ensure that library A has one pool of 10 connections available to it, component B has a smaller pool of 3 connections, an components C, D and E use the global pool with however many connections it supplies. That would ensure that no matter the number of threads running in component B, it’ll never starve out other components trying to access the database. It can never hold more than three connections, leaving room for other components. Of course, in the common case, we do want all connections to be shared in one single pool. But perhaps not always. So yes, there should probably be a globally accessible default pool available. But why shouldn’t it also be possible to define new local pools if the user deems it necessary? Why limit ourselves to one instance?
And even if you do come up with some case where we absolutely must never have more than one instance, where it would make the sky come crashing down on us, consider testing. Consider that each of your unit tests should set up the environment it needs, and run within that environment, in isolation from other tests. That means that every test should create its own logger instance, or database pool instance, or whatever else our singletons are doing, just so it can avoid being polluted by stateful changes made by earlier tests. Each unit test for the Direct3D renderer should set up its own renderer object. Each physics simulation test should initialize the physics engine first, and shut it down again after use. Singletons don’t easily allow that. Sure, we can extend them with explicit Create() and Destroy() methods, but then our abstraction is starting to get leaky. We can no longer assume that precisely one instance exists, because we might have just destroyed the one that existed.
The “exactly one instance” guarantee removes flexibility from our code that we may need, in order to enforce a constraint that we definitely don’t need. Where’s the harm in allowing the user to create more than one instance if he decides to?
C++ programmers are familiar with std::cout, the standard output stream. Funny thing about this, it is a simple global object. We can obviously never have more than one standard output stream. But we can have more than one stream. The standard library just initializes one of them to point to the standard output, and saves it as a global variable. We don’t need it to be a singleton, we don’t even need it to be a static class specially defined for the purpose. We just need a stream, defined somewhere where it’s globally accessible.
True, a sufficiently stupid programmer could create a new stream when he intended to write to std::cout, and true, a singleton implementation would have prevented that. But is it worth it? When was the last time you saw someone accidentally invoke std::ostream() << "Hello world";, when they intended to write std::cout << "Hello world";? It’s not the most common typo I’ve seen.
We don’t need to prevent multiple instantiations. If we want only one instance, we just instantiate the class once, and refer to that instance whenever we need it, end of story. We don’t need the compiler to slap us over the wrists if we do create multiple instances, because we never do so by mistake. If we do it, it’s because we have a reason. It’s because our initial assumption that only one instance was needed, turned out to be wrong!
So there you have it. A singleton combines two negative qualities. It takes the “you can never create a second instance of this class” constraint, which hardly ever makes sense, and even when it does, does not typically need to be enforced by the compiler, and combines it with a global object, giving us all the downsides of both!
Two wrongs don’t make a right. Not even if they were described as a good idea by some guys 15 years ago. They’re still no greater than the sum of their parts: two wrongs. One bad thing combined with another bad thing, creating a very bad thing.
Too many programmers rely heavily on singletons to solve a problem they never had. They never needed a compile-time guarantee that multiple instances of a class can never be created. They just needed one instance to be created.
Sometimes, we do need globals, yes. In those cases, make old-fashioned globals. Use static class members, or if the language allows it, global (non-member) objects. Or use the Monostate pattern, or whatever you feel is the cleanest solution. But remember that the problem you’re trying to solve is “enabling global access to this data”. No more, no less. You do not want a solution which sneaks completely unrelated constraints and limitations in through the back door.
And while I can’t personally think of many cases where this is true, you might also run into situations where it is truly necessary to prevent more than one instance of a class from ever existing. Again, I can’t think of what situation this might be, but I won’t rule out that it can occur. If it does, then enforce that constraint alone. But don’t go around providing global access to the object as well. Whatever specialized purpose your “one instance only” class serves, it’s highly unlikely that everyone should be allowed access to it. So don’t make it a global.
Most of the time, your classes should have neither of these attributes. Sometimes, rarely, they may need one of them. But the singleton pattern imbues the class with both properties, and that is just a plain bad idea.
Tags: c++, design patterns, singleton, stackoverflow





Aw, shucks. :P
I think your’e getting a lot better at making your argument against Singleton. I think the reasons you’ve laid down in your blog post are very coherent here, at least moreso than your arguments on SO have been in the past. Although, it’s been several months since I’ve read your arguments on it.
I see your point now and mostly get it. However, there is one reason that you didn’t address that might defend a singleton.
Programmers are people, and people do silly things sometimes. People may try to create more than one of something where there should only be one of. The advantage of the singleton idiom in that case is that it people-proofs part of it in some basic programming/use cases, say when outside users are working on a library that you wrote. In a library, you may wish to suppress multiple copies of a single object. One can actually enforce this, idiomatically, with the Singleton pattern. If one simply tried using globals, multiple copies could occur without the designer of the class allowing it, leading to some confusion. Note that the developer of the class wouldn’t use the object as a singleton, as he/she would need to unit test it.
Using a global as a substitute works well if your programmers understand the code base well enough to know that they shouldn’t make another instance of that object. You assume, I guess, that the programmers are smart enough to figure that out. I’m still unclear in my mind whether or not that’s a good assumption to make.
Maybe you can think of a counterargument for this.
Perhaps I can. It depends on what kind of assumptions you’re willing to make about the people who have access to the code.
I like to assume that people using my code are competent. I’m not naive enough to actually believe it to be the case, but incompetent developers will manage to break the code no matter what I do, so why bother with them?
But what situations can you imagine where the library developer might know that only one instance makes sense, but where the library user would nevertheless instantiate multiple objects?
Usually, the “you only need one instance” information is conveyed easily through simple naming and/or documentation. If I know that an object is responsible for, say, rendering all objects in my scene graph, then it is pretty intuitive that another instance won’t have access to the same scene graph, and so won’t be very useful. As a library user, I know intuitively that this one object is all I need, because it is associated with the data I want it to be associated with.
Or take the
std::coutexample from my post above. You’re right, a sufficiently dumb library user could instantiate anotherstd::ostreamwhen he intended to write to the standard output, but in reality, it just doesn’t happen, because real-world users of the standard library know thatstd::coutis the standard output stream, and they know they only need that one instance.Can you think of a situation where the library user might mistakenly believe that creating multiple instances is warranted? I can’t. I won’t rule out that such situations exist, but in the common cases (see
std::cout) it isn’t an issue.It’s not that I assume programmers in general are smart enough to figure out how to use my library. It’s just that those who aren’t will manage to break it no matter what I do. Sure, I could sprinkle singletons all over it, but that still wouldn’t save them from themselves. There are still hundreds of ways in which they could break my library: passing invalid parameters to functions, freeing resources allocated by the library and so on.
Of course, a final point is that you’re not arguing for a singleton. You’re arguing for a “class-that-enforces-that-exactly-one-instance-will-exist”. That’s only half of the singleton. The singleton also provides global access. If you really think that enforcing the 1-instance-limit is best, then do that, but how does that excuse making the same object globally accessible?
Ah, you did write about it — nice to see your arguing collected in one article.
Good points made, especially the ones relating to cout vs. ostream. I personally feel the “what if another instance of the thing can’t be instantiated” is a weak argument; the construction of an object should require enough context to get a useful object, so if someone wants to create their own Logger instance that’s fine– but they’ll need to configure it properly if it’s going to do anything useful and it should be obvious to anyone who spends ten minutes in the code that that’s not how everyone else gets their messages out to the world.
Anyway– I see Singletons as additional complexity on top of the overwhelming complexity that mutable global state itself brings. I don’t want that mutable global state in the first place, so Singletons bring no value to me, personally.
I don’t think ignorance of the codebase is a fruitful argument, one way or the other; people will do whatever they want to do, and sometimes people screw up. The best way to code (IMO) is such that screw ups are shown quickly and obviously. Globals tend to make this more difficult, as well.
The most useful statement made, I must say, is that of artificially constraining your objects. What’s the problem if someone instantiates another instance of this class? (and if they do it wrong, report the error promptly and unambiguously!)
What I’ve taken to saying lately is that Singleton should be an Application design question rather than a Class design question. If in your specific application it’s convenient to have one globally-accessible instance of a certain type, that’s great, but there’s no reason to write the class in such a way that the class needs to know about that decision.
Of course, that doesn’t prevent someone using another instance, but if the application is architected that way, you can’t get the other code to use the instance you created even if you wanted it to.
BTW, it might not be a bad idea to write a bit about dependency injection to add to your singleton rants, since that’s in many ways a “do this where your current instinct is a singleton, and you get all these advantages”.
Thanks for sharing this. You definitely have a point and I will consider never to use a Singleton again.
I started studying OOP less than a year ago. So, it is not difficult that all of you are more aware of it than me.
IMHO, I think it is not a bad idea to use Singletons in order to avoid having multiple instances of an object (i.e. the Model) and have a global access to the single instance.
I agree with you about the fact that Singletons increase hidden dependencies. But I also think you can solve the problem getting those dependencies visible. Don’t you think you can assign a singleton instance to a member variable of a class that needs it?
Doing so, you make the dependency visible and give yourself the opportunity to remove the single instance constraint if you made a bad assumption about it.
Does it make sense? Do I have to apologize for my english? :)
@Adriano: Why do you need to “avoid” having multiple instances of an object? I don’t need to do anything to “avoid” jumping into the sea. I don’t need to do anything to “avoid” buying a plane ticket. Those things only happen if I decide to do them. And likewise, instances of an object only exist if I decide to create them. If I only need one instance of an object, why would I create two? Why do you feel that you need to do anything special to “avoid” creating multiple instances?
The second part, about global access, is somewhat more subjective. Perhaps you really want global access to this object. In that case, go ahead and make it global. I think global access is nearly always the wrong thing, but it really doesn’t matter. If you want global access, use a global. If you don’t want global access, don’t make it a global. Neither case requires a singleton.
Sure, you can do that. But then (1) why does it need to be a singleton, why does it need to be globally accessible, and (2) you still have no way to ensure that it’s never used in the “other” way. That’s what’s icky about singletons. You don’t know if these hidden dependencies exist. They might all be made explicit as you expect, but there might also be a number of“hidden” uses scattered around your code. You don’t know.
So say you need access to a Settings class at various hierarchical levels in your code, for instance the Application, the Controller and the View. You could have a globally accessible Singleton and have code like:
Or you have it be an instance var on the Application class which is referenced by an instance var on the Controller class which is referenced by an instance var on the view and so on… You end up with the following:
Which is a (very!) hidden dependency. Or you do…
…and create tons of code with a multiplicity of by way of property names, making changes such as refactoring a serious sweat.
What I’m asking really, is what about the case for the singleton (or at least a global variable) where it reduces complexity for application areas which aren’t resource intensive?
Like many things in programming isn’t it a trade off between simplicity and covering all potential future cases?
How is the first one a hidden dependency? It’s clear exactly how the current object retrieves the settings object. We know that it does this through its reference to the parent controller, which has a reference to the parent application, and so on. We have explicitly said in the code that this code requires a reference to the parent controller, so it is not a hidden dependency. I can look at the object’s constructor and see that it takes a reference to the object it needs to reference. Or I can follow the code the other way around: Start at wherever the
settingsobject is created, and then read along to see where it is passed to. If I follow the code from that point, it naturally takes me to every use site.On the other hand, in your second snippet, it’s not clear where this settings object comes from. And I can’t follow the uses of the object. If I start at the construction of the
settingsobject, I immediately run into “it’s stored into a singleton, which is… just there. At some point, someone might callgetInstanceon it, but I don’t know who does that, or when or why.So I disagree with your analysis of dependencies.
On the other hand, it is certainly more convenient to just make the settings object globally accessible.
So go ahead and do that. But it doesn’t need to be a singleton to achieve that goal. Just a single global/static instance will allow everyone to access the settings object if they want to. There’s no need for messing around with singletons and all the other problems they cause.
Singletons are global, but globals are not singletons. If you need a global, that doesn’t mean you have to use a singleton.
Hidden in the sense that the lowest level object which is making the call now has 2 more dependencies in addition to its dependency on the settings class — perhaps not hidden from it’s perspective but from the top level vantage point, doesn’t the dependency on Settings seem quite buried? Say you changed the structure of the settings object and needed to find all referencing code…
At first I was inclined toward your stance on using a simple global variable which is init’ed perhaps, with the app startup. Upon reflection however, I’m not sure I see the difference between this and the singleton pattern, other than that the later packages the global variable (as a static) and has a self contained initialisation. Some might even argue that this is more in keeping with Single Responsibility Principle. What do you think?
Thanks for the thought provoking and detailed discussion by the way. It’s very pertinent to the code I’m writing as we speak :)