I’m Adam, and i’m a recovering Singleton addict.

My name is Adam, and i’m a recovering Singleton addict.  There, i’ve said it.  I used to use singletons all the time  because they make doing some things, like sharing state globally, incredibly convenient.  My code was littered with XYZManager classes.  The defining trait of these classes was the static GetInstance() method that magically enabled me to get access to that object and its state wherever I wanted!!  What a great idea, right?

What a mess!  I learned over time that the cost of changing one of these things, or the cost of doing a major refactor was really high in terms of code change.  And to make things worse, because my classes’ dependencies were hidden in implementation and weren’t transparent in the interfaces it was impossible to write real unit tests.  This made doing a big refactor even less attractive.

So over the years, through work in the industry and coding on my own I’ve come to the conclusion that the singleton sucks, and that there are very few places where they are actually appropriate (logging comes to mind as one acceptable place).  The fact of the matter is that most of the places I see singletons used in software they are actually just an enable for developer laziness.

So here is my off the cuff list of why singletons suck.  Feel free to comment and add your own reasons (or counterpoints)

  1. Singletons hide your dependencies.  This makes code harder to understand
  2. Singletons make unit testing difficult.  It’s hard to mock out a global object that you can’t inject into a class
  3. Singletons reduce reusability.  If i’m writing a class that utilizes a singleton because my application will only ever use one then i’m limiting myself because I can’t use that library to write test tools that may want to simulate how many of these object (for instance, many users) interact with a system.
  4. Singletons reduce scalability.  A single, global object?  Sounds like a source of contention to me.
  5. Singletons are not good object oriented design, they are lazy!
  • NoBody
    • Sloughin

      My name is Steve and I’m a Singleton addict… and no, I’m not yet in recovery.
      So it’s all very well and good to criticize the Singleton Pattern, and while I will admit to having [over]used it (is that a redundant adjective?) I still find it darn useful, and haven’t found any other tool in my programmer’s kit to replace it.

      Example: I’m writing a Windows app and I need to keep track of settings that get passed on the command line, that trump user-specific settings that are stored in a user settings table, that trump app-default settings stored elsewhere. All that parsing and trumping is a lot of work, and then I need access to all those settings all over the app. Having a singleton allows me to do the parsing and trumping once on app load, and then get my settings wherever I need them.

      So, while I know everyone loves the stateless app, a computer is, after all, a state-machine. If you won’t let me have my singleton-fix, then tell me where to buy my method-one.

      • http://profiles.google.com/kristoffel.pirard Kristoffel Pirard

        Designing your app to do settings initialization “Once on app load” is nice. But Singletons gave us a hard time to re-design our app do e.g. Multiple Documents interface. In the end, we even gave up on it.

        I admit it’s a lot more code, it’s a lot more function arguments/member variables etc… without Singleton. But with proper interface/implementation separation, it’s not really _complex_ to ‘forward’ your settings, or even parts of your settings, into your application’s domain classes.

        Your method-fix can be bought at the ‘go-through-all-needed-code’ store. It has a price. It has it’s merits.

      • http://adamschepis.com Adam Schepis

        @google-635c3ea0c7b8c37ef45744b6e66dd263:disqus beat me to it! You are storing user settings for your app. What if your app needs to communicate with a backend somewhere (as so many apps do these days) and the user settings affect this. When you write your code to do load testing wouldn’t it be great if you could simulate hundreds of users in a single process and have them all have their own unique settings? And wouldn’t it be even better if you could reuse the code you already wrote? If you have a Singleton for that user settings object, this isn’t possible.

        Admittedly there is a thin line between what is needed now and what will be needed in the future, but building reusable code from the start reduces your technical debt as your project evolves and matures.

      • jalf

         I can see two obvious problems with this approach: #1: making your settings a singleton means that it is impossible to have “not-currently-applied” settings. Say the user enters the “settings” dialog, and changes a few settings. But he didn’t click “apply” yet. Without a singleton, you could handle this easily. You could have “the settings currently in effect” represented by one Settings instance, “the settings that the user is currently defining” as another instance, and “the profile I want to be able to switch to when I’m on *this* network, or when I’m at work, or when my grandmother needs to use my computer” as further instances.

        Without singletons, you could easily define a single global instance representing the “currently active settings”, but you could *also* represent all the other settings in your app.

        And problem #2: why does *every* part of your app need to know about *all* the settings? It doesn’t. But thanks to the blessings of the singleton, your code has degenerated into dependency spaghetti. And thanks to your singleton addiction, you consider this a *good* thing.

  • http://twitter.com/codemonkeyism Stephan Schmidt

    I think you need to distinguish between GoF Singletons and say Spring framework Singletons. The later ones might have the same problems concerning global states, but do not show the other problems. When build against an interface, dependency trees get smaller, when injected mocking is easy and unit testing no problem.

    Best
    Stephan
    codemonkeyism.com

    • http://adamschepis.com Adam Schepis

      Good point, Stephan. Although in Spring you can create an object with Singleton lifetime, I don’t view these objects as singletons in truest sense. It is just the only instance of it created by the framework and so it doesn’t have the same limitations of a true singleton. Additionally, if it turns out that singleton lifetime isn’t right for that object its very easy to change. Since you’re injecting it into the necessary places already as an instance the only change is in your Spring config.

    • http://adamschepis.com Adam Schepis

      Good point, Stephan. Although in Spring you can create an object with Singleton lifetime, I don’t view these objects as singletons in truest sense. It is just the only instance of it created by the framework and so it doesn’t have the same limitations of a true singleton. Additionally, if it turns out that singleton lifetime isn’t right for that object its very easy to change. Since you’re injecting it into the necessary places already as an instance the only change is in your Spring config.

  • Matthew Towler

    Around 2000 I implemented a whole system architecture using singletons, later arriving at exactly the same conclusions and learning a lot from the experience. At that time I was not unit testing and reusability was not an issue so it was not immediately obviously a bad idea. It was an embedded system so the boundaries of use and lifetime issues were not present

  • https://me.yahoo.com/a/mHHNaVY.rPg32F_gPb9hQklgokmhjXs-#71388 me

    Sounds like your next addiction will be Dependency Injection…

    • Waylon

      Which beats Singleton addiction, anonymous snarky person. Refactoring is much easier in a design featuring Dependency Injection. The code base is more maintainable and the overall health of the code improves. It’s better to be addicted to kale than cola.

    • http://adamschepis.com Adam Schepis

      Dependency injection is just a mechanism for simplifying good object oriented design. If you design classes that make their dependencies known then you have the option of using dependency injection to facilitate the creation of your objects. That’s not a bad thing, nor does it box you into a corner.

      • http://www.openmymind.net/ Karl Seguin

        No. DI is a mechanism for decoupling when the language doesn’t provide any built-in decoupling capabilities.

        Saying that DI is a mechanism for good OO design is like saying delete is good design for proper memory management. When you move to a runtime which provides automated garbage collection (and doesn’t provide a delete keyword), you aren’t doing “bad design” – you are simply moving to a more productive platform.

        I find it ironic that, on the one hand, you’re willing to admit that one of the tools in your toolbox (singletons) is evil…but on the other hand, don’t question another fundamental tool in your toolbox (DI). Your singleton discovery should make you realize that for all you know, 2 years from now, you *will* consider yourself a recovering DI junkie (and trust me, you will).

        Your blog post made me blog:
        http://openmymind.net/2011/5/3/Dealing-with-Now-and-why-i-am-almost-done-C%23-and-J

        (I’m latch from the HN comments, btw).

        • http://adamschepis.com Adam Schepis

          Karl — I liked your blog post a lot and I think that it is a nice illustration of some of flexibility of Ruby vs. languages like C# and Java. I’m a huge Ruby fan and user. I think that your example of mocking the Time class does illustrate a limitation of Java and C# vs. a language like Ruby (although I think that the limitation is probably intentional.) Cases like this are certainly examples of places where for completeness we need to Unit Test

          This all being said, i still disagree with some of your points above.

          First, please don’t mistake my differing opinion as being born from a lack of rigor on my part. I’ve certainly put some thought into DI and what my opinion of it is.

          I don’t view DI as a mechanism for decoupling. I view the class design phase as the mechanism for decoupling. DI is just a tool that can make hooking up those dependencies easier in some cases. You could just as easily instantiate an object and set the appropriate dependencies yourself, or create your objects with smart defaults for dependencies so that you can still mock them in tests or change the implementation when necessary.

          I see this pattern in Ruby as well. For instance, on one of my personal projects right now i’m using the rightaws gem to interact with SimpleDB. Almost all of of the rightaws classes and interfaces allow you to set the Logger to use. It defaults to the Rails (2.x) logger so that things just work if you’re within Rails, but it makes the dependency known via the interface and provides a mechanism to replace the default with your own Logger implementation if you need to.

          Second, I don’t think that DI is a *fundamental* tool in my toolbox. Truth be told, I have only used it (Spring, particularly) at work on some Java projects. Oddly enough, I also inherited a project where Spring was badly misused and we tore it out.

          I definitely appreciate your viewpoint and contribution to the conversation (here and on HN) and, trust me, if in two years I have come to despise DI I will be the first to admit it, and you can give me a hearty “I told you so!”

        • Schev

           You have made a very common mistake.  Don’t confuse dependency injection with dependency injection frameworks, ie IoC containers.

          A class that exposes its dependencies as say parameters in the constructor is fundamental sound engineering.  Whether you need a container/framework to inject the dependencies is a separate topic

  • speculator

    Friends don’t let friends do singletons.

  • Jvansanten

    multithreading…

    • http://adamschepis.com Adam Schepis

      Are you saying that multi-threading is another reason that the singleton is bad? I completely agree and was alluding to that when i mentioned how singletons reduce scalability. You can certainly make a singleton class thread-safe, but those locks are going to be awfully hot if your singleton gets a lot of use. thats going to kill performance.

  • Anonymous

    Object Oriented Programming, in whatever language, is really a set of concepts and rules which facilitate best practices. Often these best practices aren’t taught too well, if at all, in school, and most professionals are lucky if they learn them through mentors, reading, etc. Specifically, I mean basic things like data hiding, partitioning responsibilities / modular decomposition, hierarchical design, design for testability, etc. The Singleton is a design pattern for a global variable, and experienced coders all come to the conclusion that global variables should generally be avoided and used in only limited cases.

    • Patrice

      I agree except for the phrase: “The singleton is a design pattern for a global variable”. I would phrase it as “The singleton is a design pattern that can be used to replace global variables” and I agree with the rest of the sentence. The fact is that there are cases where you want to ensure that there is a single instance of an object in the system (hardware abstractions being one of them) an in those cases the singleton pattern is the way to go.

      • http://gregturn.myopenid.com/ Greg

        When you say a single instance of something, I point to Spring and how easy it is define one instance in your context without resorting to the ugly and leaky singleton pattern. By NOT using the singleton pattern, code again becomes testable.

        • Louddwarf

          Being an amateur programmer I’m going to ask an amateur question….

          What’s Spring?

        • Patrice

          This kind of suggestion would have made this post a lot more useful. However I fail to see how using dependency injection would prevent one from using a single instance object as a substitute for global variables. Am I missing something?

          • http://adamschepis.com Adam Schepis

            It avoids the Singleton pattern, which limits you to have a single instance for your entire process.

            I’ll try to illustrate with an example (sorry if it seems contrived.)

            Imagine you have a client process that stores some data for a user and keeps it in sync with a server somewhere (like dropbox, or evernote.) When your application is running you may want to have a single instance (maybe because it writes to a single file, or has some kind of synchronization constraint.) So you choose a singleton pattern, or you use DI (or just plain old setters and getters) to get that object into the objects that depend on it.

            Either will work great… Until you start writing load testing or automation tools to test your server. Now if you have chosen the singleton pattern you literally *cant* have more than one instance of the object in your process. If you used DI for your application you can just opt not to use it in your automation app and instead create a new instance of the object (that writes to a different file) for each user you want to simulate. Now you can have a process that reuses your code and can simulate many users and test that against your server. This solution has good code reuse, and is DRY (Don’t Repeat Yourself.)

  • Dale

    I would generalize this to public static fields of any kind.

    • Harley Pebley

      +1

  • Anonymous

    The arguments against the Singleton seem abstract and unconvincing.

    In one of the links (below) The use of Singletons in the Gang of Four book is criticized as only meeting the needs of the applications cited, and not meeting future (hypothetical) needs. This is a violation of the YANGNI principle (You Are Not Going to Need It) of Extreme Programming, which observes that meeting hypothetical future needs is often a waste of time.

    Another criticism is that they’re similar to global variables. But the scope of the Singleton is limited to a CLASS, avoiding the collisions in the global namespace that true global variables cause.

    I’ve seen situations where substituting a Singleton is an elegant solution to a problem. Just the fact that it can be misused doesn’t make it an antipattern.

    • jalf

       No, YAGNI says that you should not add complexity to your application in order to accomodate future changes. And that is exactly what a singleton is for. Singletons are complex, especially if you want them to be correct (and if you want them to be thread-safe as well, you’re bordering on rocket science complexity.). So, according to YAGNI, you should not add this complexity, and you should not add features and constraints (such as the one-instance-only restriction that defines a singleton) until you absolutely know you’ll need it. You’ve got it upside down. If you care about YAGNI, then never, ever, write another singleton.

      • Anonymous

         No, the Singleton is the SIMPLEST design pattern.  If you want a thread-safe Singleton, just use a lock statement.  YAGNI only applies to Singletons you’re not going to need.  If you need it, use it!

        • jalf

           Then give me *one* simple example of when you need a singleton (and tell me why a simpler global, or even plain old local parameter passing, aren’t viable options). I’ve never ever seen such a case. It’s always added complexity on top of what was actually needed.

          • Anonymous

            I once “inherited” C++ code that created new objects for every iteration, making it hard to watch them in a Watch window.  A singleton would have fixed this.

            Global variables could have been used, but if the code is merged with code written by someone else who also used global variables with the same name, someone has to go through one of the code bases and change EVERY ONE to a different name.  (This happened to me a long time ago, and was a lesson in minimizing global variable usage.)

            The difference is that a singleton doesn’t “pollute” the global variable namespace; its variable(s) are encapsulated in a single class.

            Another case where a singleton is useful is for variables that consume lots of resources, but are infrequently used.  The lazy initialization avoids wasting resources unless they’re needed. 

            Here’s the elegant part: With a singleton, you don’t have to worry about whether it’s been initialized EVERY PLACE it may be used.  You just use it.

          • gf

            This still doesn’t require a singleton, just a (possibly lazily created) global. Write a class for encapsulation, provide convenient global access to it, done. No need for enforcing “only one instance” as part of the class’ design.

  • Patrice

    This post reminds me of the saying “Food is evil: it makes you fat”.

    It’s not the singletons that are evil, but the usage you make of them. If you use them to replace global variables and pass information outside of the call chain, that’s bad design, but it’s not the singleton’s fault.

    This post would have been useful if it had described the cases where singletons should not be (ab)used, and more importantly what you use instead.

    • http://gregturn.myopenid.com/ Greg

      “f you use them to replace global variables and pass information outside of the call chain, that’s bad design, but it’s not the singleton’s fault.”

      This is how virtually every singleton I ever saw was used, whether mine or other developers. The risk of using it in this fashion is huge; hence the reason people call it an anti-pattern.

    • Harley Pebley

      I’ll flip the question around and ask you, “Where do you think singletons should be used?”

    • jalf

       It’s not a question of “is this the singleton’s ‘fault’” (whatever that means. You’re the one who wrote the code. it’s your fault, by definition, if there’s a problem). It’s a question of “would the code be better if I didn’t use a singleton?”

      I’ve never seen a case where a singleton made the code better. And thus, I consider it an antipattern. I see no reason not to.

      • Jeroen vd Sloot

        The (N)Hibernate SessionFactory will be a singleton in your application, I hope.

  • Damith

    You may be happy to know that Eric Gamma (one of the GoF) himself says if he were to refactor design patterns they put in the famous GoF book, he would drop Singleton. http://www.informit.com/articles/article.aspx?p=1404056

  • SeattleC++

    Don’t forget that it’s difficult to implement singletons correctly in a multithreaded environment. The whole double-checked locking antipattern is about singletons.

    • Asif Mushtaq

      +1

  • Harley Pebley

    Every time I’ve used a singleton, I’ve come to regret it later. Even for logging.

    • Helen

      …because you don’t know how to use them? A singleton is a tool. and you have to understand when and how to use them. I’ve seen guys trying to hammer in a nail with a crescent wrench. Don’t blame the tool.

      • Harley Pebley

        True statement. I used to think there was nothing wrong with using them on a regular basis. However, I found Singletons are like narcotics. They work well to overcome short term pain. But if you live on a steady diet of them… well, the first step to recovery is admitting there’s a problem. ;-)

        First, a class using a singleton cannot use something else. And ideally you always want to use something else when you unit test the class using the singleton. You are doing unit tests, right?

        Second, the singleton pattern violates the Single Responsibility Principle. It places the responsibility of the object’s lifetime within the object, along with the object’s other responsibilities. Every singleton has to be responsible for not only its reason for existing but also for managing its own lifetime. Would we make every object responsible for all its memory management? No. We delegate that responsibility to memory managers, even in languages with malloc in their libraries. In these cases malloc is still handling low level memory management issues. In the same manner, object lifetime should also be delegated to another system.

        Thirdly, requirements change. In my experience, every time the requirements made it look like a singleton was appropriate, and it was used, they changed later such that the singleton behavior had to be removed and everything referencing it had to change to reference a non-singleton instance.

        Bottom line, I don’t blame the tool. I just recognize that in the case of this tool, it needs to be used very, very judiciously, in limited quantities, for short term purposes and should be eliminated from the diet as soon as possible.

        • Lukasz

          Doesn’t this trivial code (C#) solve all your three problems?

          class ObjectFactory
          {
          public static ICustom GetCustomInstance()
          {
          return (ICustom)Singleton.Instance;
          }
          }

      • jalf

         But a tool has something it is good at. A hammer is a tool because we can use it to hammer nails into walls. And a chocolate hammer is not a tool, because it can *not* be used for this. Simply having the potential for misuse does not make something a worthwhile tool. So where is the redeeming quality of singletons? Where does a singleton become beneficial? When does it become a tool, rather than a liability?

        If you have a “tool” that can never be used to solve a problem, then, well, you can keep it. And I disagree with calling it a “tool”.

  • perfection? what is it?

    What do you do if you have a class that depends on another? That dependency was a singleton and so the alternative is to pass in a pointer in that references that class(member parameter who gives a crap). Would that be acceptable?

    I’ve seen some people on gamedev irc would rather prefer this. I’m guessing something like this could help refactoring a case where the class is still needed but not a global singleton based(say that singleton has to be many objects now).

    void function()
    {
    SingletonClass *s = SingletonClass::GetInstance();

    s->blah
    s->blah

    instead of

    void function()
    {
    SingletonClass::GetInstance()->blah
    SingletonClass::GetInstance()->blah

    then bam you replace get instance with whatever you want or… ditch it all together gone.

    The other way to defeat a singleton is message passing which decouples the objects… But If I saw a texture manager using a callback way of getting textures(AKA message passing). My eyes would roll and I would again wonder why I ever became a programmer.

  • OldWiseLlama

    I generally don’t like to use the term singleton even when I’m talking about a single instance of a class in a certain scope. The term singleton always reminds me of something like: SomeClass.Instance.DoSomething(). I think this kind of code has a smell.

    Let’s assume that the afore mentioned SomeClass would be a logger. Now what is the responsibility of a logger? Well of course it is logging. And last time I checked logging doesn’t contain the responsibility to force the existence of a single instance of itself.

    There could be only a single instance of a logger class but there are much better ways to accomplish this in my opinion. For example let the IoC container or one of its dependencies worry about only having only a single instance of that logger exist at any one time.

  • http://profiles.google.com/florin.jurcovici Florin Jurcovici

    Idunno … have you considered using Spring? It’s available both for .Net and Java, and it’s great for dependency injection. It also allows one to use singletons without coding their classes to the singleton pattern. (You also have plenty of other IoC containers available for Java, I don’t know about .Net.)

    Coded carefully, singletons can be of great use. Most apps consist mostly of CRUD code. In such cases, an anemic model is justified (http://codebetter.com/gregyoung/2009/07/15/the-anemic-domain-model-pattern/), and using singletons for services which mostly encapsulate the tiny business logic there is is a convenient way of creating efficient code for the server.

  • http://profiles.google.com/florin.jurcovici Florin Jurcovici

    Provided you do it right, it allows you to do more than that. You could make your singleton responsible of writing changed settings back to disk, or to whatever places they need to be written to, and provide an interface for other components to listen to changes in the settings. You simply couldn’t do this without using singleton.

  • Pingback: I’m Adam, and i’m a recovering Singleton addict. - TextChannels

  • http://www.facebook.com/people/Luiz-Felipe-Stangarlin/1550900045 Luiz Felipe Stangarlin

    Singleton is like Global Variables. Avoid like a plague!

  • AAA

    if you need one object go static methods. no singletons needed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • Pingback: Singleton is an anti-pattern | Molecular Musings