Why Singletons are Evil


While I did not write this, I totally agree with it. Brian Button is probably one of the most talented people I know, and I am sure he would love your feedback.

1)       Singletons frequently are used to provide a global access point for some service.
True, they do this, but at what cost? They provide a well-known point of access to some service in your application so that you don’t have to pass around a reference to that service. How is that different from a global variable? (remember, globals are bad, right???) What ends up happening is that the dependencies in your design are hidden inside the code, and not visible by examining the interfaces of your classes and methods. You have to inspect the code to understand exactly what other objects your class uses. This is less clear than it could be. The urge to create something as a global to avoid passing it around is a smell in your design; it is not a feature of globals/singletons. If you examine your design more closely, you can almost always come up with a design that it is better and does not have to pass around tramp data to every object and method.

2)       Singletons allow you to limit creation of your objects.
This is true, but now you are mixing two different responsibilities into the same class, which is a violation of the Single Responsibility Principle. A class should not care whether or not it is a singleton. It should be concerned with its business responsibilities only. If you want to limit the ability to instantiate some class, create a factory or builder object that encapsulates creation, and in there, limit creation as you wish. Now the responsibilities of creation are partitioned away from the responsibilities of the business entity.

3)       Singletons promote tight coupling between classes
One of the underlying properties that makes code testable is that it is loosely coupled to its surroundings. This property allows you to substitute alternate implementations for collaborators during testing to achieve specific testing goals (think mock objects). Singletons tightly couple you to the exact type of the singleton object, removing the opportunity to use polymorphism to substitute an alternative. A better alternative, as discussed in the first point above, is to alter your design to allow you to pass references to objects to your classes and methods, which will reduce the coupling issues described above.

4)       Singletons carry state with them that last as long as the program lasts
Persistent state is the enemy of unit testing. One of the things that makes unit testing effective is that each test has to be independent of all the others. If this is not true, then the order in which the tests run affects the outcome of the tests. This can lead to cases where tests fail when they shouldn’t, and even worse, it can lead to tests that pass just because of the order in which they were run. This can hide bugs and is evil. Avoiding static variables is a good way to prevent state from being carried from test to test. Singletons, by their very nature, depend on an instance that is held in a static variable. This is an invitation for test-dependence. Avoid this by passing references to objects to your classes and methods.

I hope this explains a little more fully my opinion of the singleton pattern. I have a small collection of links I found through Google of others, including Jim Hyslop and Herb Sutter, who share this opinion. Let me know if you’d like them.

[Now Playing: Metallica – Disposable Heroes (08:17)]

Comments (44)

  1. Scott Allen says:

    I agree singletons are the source of many problems that start in design and end in debugging. I certainly agree with point #1 and #4. As for #2, and #3, I don’t find those points as convincing. I could be bastardizing the textbook definition or misunderstanding, but these points seem to imply a singleton needs to be a class with all static / shared fields and methods. I tend to think of a singleton along the lines of #2, whereby a factory returns the single instance of an object. The single object can be polymorphic which offers different implementations for the same contract established by a base class or interface.

    That being said, I’ve seen so many people in newsgroups run into problems with singletons. Many of these problems fall into point #1, whereby the problem they are solving really doesn’t need a singleton solution, but there are also threading issues to deal with, and figuring out what to do if the singleton creation process could throw is tricky.

    Could you post the links in a comment?

  2. #2 is saying Singlton is managing a resource and a factory or builder is a better "true" option for how to create a object. #3 means that everytime you use a singlton in some other class you are not tied to that singleton and everyone who uses it… and that is same problem with globals. In todays new SO environment and given that one of testings principles is isolation, tying everone to that one singleton smells bad. Singletons have there place I am sure, just not sure I have ever come across a need for one.

    And what links do you want me to post?

  3. damien morton says:

    Singletons are a great temptation, as are static classes with public methods and private state.

    I havent put this into practice yet, but I have a feeling that the IServiceProvider constellation of interfaces is a good approach to handling singletons, at least, it seems that it might be the solution in the MVC code ive been working on.

  4. Roaan Vos says:

    I like singletons and thus can’t say I agreee with everything that’s been said. As with everything misusing something does make it seem evil, but used correctly it does not have to be.

    Personally I see a singleton as a resource. E.g. Let’s assume I’m accessing one database and have a singleton allowing all access to the database. Isn’t this singleton better than having to pass a "database" class all over the code. Come to think of it, it might actaully lead to "looser" coupling since the method/class that needs access to the database can access the singleton without relying on other methods/classes having to pass the "database" object. Having the "database" class in the method signature actually tightly couples everyone to this implementation.

    To clarify. Let’s once again assume I have a class called "UserInfo" that loads user information. We have 4 options.

    1) The "database" class is passed in the constructor.

    2) The "database" class is passed to every method in "UserInfo"

    3) The "UserInfo" can have an internal "Database" member variable which has to be instantiated everytime a "UserInfo" class is created. (I.e. configured etc)

    4) The "UserInfo" has access to the "Database" singleton

    Options (1) and (2) all mean that whoever wants to use the "UserInfo" class must pass the "Database" instance and in the process tightens coupling.

    Option (3) looks ok except that the "Database" class has to be reconfigured for every instance of "UserInfo"

    Having "UserInfo" manage access to the database (either via (3) or (4)) means "UserInfo" can be seen as a standalone component that is reusable by other applications.

  5. Brian Button says:

    This idea of using a singleton to access a database whereever it is needed is the "singleton as global variable" antipattern Scott wrote about above. The main two problems I have with it are that it directly couples code to the singleton object, and it does it in a hidden way. I prefer to make dependencies between classes obvious through method signatures, if at all possible. This lets me understand a design better without having to look through the code.

    The point about tightly coupling everyone to a database implementation is not entirely correct. It does couple everyone to a database interface, but it does *not* couple them to an implementation. The interface is passed where it is needed, and I can override the interface very simply to provide one-off testing implementations of it for my unit tests.

    If I find myself having an object that is passed all over my code, that is not a sign to me to make that object into a singleton. It is a hint, taken from my code, that there is a different way I could have partitioned my system to avoid that piece of data becoming a tramp. I try to change the design for the better rather than introduce a global variable.

    Roaan, is everything you said above equally valid if you replace "singleton" with "global variable"?

  6. #1 is inevitable when your system consists of tons of services (as in tens and even hundreds). Passing them around is plain impossible, you end up with too many parameters, most of them unused (methods will be passing most of its parameters to other methods without using them).

    Alternatively, you may add a bunch of Get methods to other object intefaces in an attempt to let objects get to the service so when A needs B but only has C, it will call C::get_D, then D::get_E and then E::get_B.

    Difference from global variable is very simple and described in patterns books: you cannot modify the object. Nothing is wrong with const global variable (read: #define).

    BTW, it is much easier to refactor code with QueryService calls vs one that passes everythign around. If you don’t want code to be talking to service provider, don’t give service provider to it.

  7. Roaan Vos says:

    I would not replace singleton with global variable. The reason is more personal. All my singletons are (almost completely) stateless. The only state they contain are generally configuration settings.

    If I had to use global variables 😉 I don’t think this same restriction would apply. If the global variable had state, I would never use it. If it is stateless then I can see how global variable and singleton could be seen as the same. The problem with global variables is not that they are global, but rather the fact that anyone can change their state.

    If classes use singletons, I think it is much easier changing/replacing the singleton than replacing all method signatures in a call stack etc.

    PS. How about this as food for thought. What would the general comment be if I said in essence SOA’s are singletons

  8. Brian Button says:

    Mikhail,

    #define and const global variables are very different things. #defines do not introduce dependencies on classes, whereas variables do. I don’t understand how the cases are parallel.

    As far as your other points about having a system with many services, I fear that our coding styles may be different. I definitely tend towards lots of small, special purpose classes, which usually means that one class needs a very small number of services. I don’t run into the situation where one class needs to know about the entire rest of the world. And when I do, I take that as a hint from the code that the design is not as good as it could be, and I make it better.

    Whether you pass the objects in or use a global method of accessing them, that module is still very tightly coupled to the entire rest of your system, and is entirely untestable at the unit level.

  9. Brian Button says:

    Roaan,

    That’s an interseting point you raised about SOAs. In essence, I agree with you on that. Once again, I prefer to find a way to make their presence known, and to limit their reach into the rest of my code, as with singletons.

    The issue I try to mitigate when faced with a static dependency like this is the tight coupling that this puts onto any code that calls this. Since singletons, statics, and SOAs are all direct dependencies, without the benefit of an interface on top of them, I always try to interpose a shim class over them. I create an interface for that class, and then I can use a special testing version of that class during unit testing, so I don’t have to access the network, set up a server, etc. The downside of this is that I then do have to pass that service around to where it is needed. In my mind, though, that just makes public a dependency that was already there.

    Most of the complexity I end up adding to systems I do to make the final system more unit-testable. I find that the act of doing this also takes me down other good roads, like forcing my code to be more modular, eliminating spiderwebs of dependencies, and things like that. All Good Things (TM).

  10. Mikhail,

    I aggree with you on that. I am assuming you are talking about Visual Studio with QueryService. I think this is a good way to use singltons, and the cool thing about this is I really don’t know that I am using one as far as the service is concerned. I guess this might also be concidered as a facade into my service (whatever that might be), and I agree with this approach. Of course I love Visual Studio so I guess the QueryService part does not bother me. :). Thanks for the feedback.

  11. Scott Densmore has an interesting post regarding singletons and why he thinks they are evil. I’d like to go through his points one by one and add my thoughts: Singletons frequently are used to provide a global access point for…

  12. Button’s Law of Design Maturity

  13. I know the title of this post is weird, but just bear with me a moment… Often time I found myself writing

  14. Design Patterns – A deep dive 3

  15. Rob Conery says:

    Seems I touched off a bit of a “swirl” with a comment I made on my last blog post: I think, in general