By paddloPayday loans

Home > ActionScript, Design Patterns, OOP, Singleton > Singletons Give You Pimples: Why to Avoid the Singleton Pattern in ActionScript 3.0 Programming

Singletons Give You Pimples: Why to Avoid the Singleton Pattern in ActionScript 3.0 Programming

At the 2006 OOPSLA Conference in Portland, Oregon one of the people who came into our session was pounding on the Singleton Design Pattern. He even brought in a PowerPoint presentation quoting Erich Gamma as saying he wished he’d never included the Singleton in the GoF book. This wasn’t a mild rebuff of the Singleton; it was a wholesale condemnation.

The Singleton in ActionScript 3.0

A quick online search reveals a good deal of discussion about the Singleton in ActionScript 3. However, much of that discussion is based on how to improve it given AS3’s lack of private class constructors. Both Grant Skinner and Tink have provided brilliant workarounds that seem to solve the problem of multiple instantiations of a Singleton. Darron Schall has written a nice summary of the ActionScript 3.0 Singleton discussions and reached a similar conclusion as I originally did. Namely, most of the problems envisioned by ActionScript 3.0’s lack of private class constructors never caused the problems that AS3’s shortcomings were supposed to have caused. In our book, we provide a brief cautionary tale about using the Singleton, but it was not very strong or substantive. (I wrote the Singleton chapter; so I can say that.)

Any attempt to improve the Singleton is like making the black mamba more deadly. The point is not to improve it but to avoid it. However, in understanding the problems using the Singleton, we can better understand what the focus of OOP programming should be and the reason that using design patterns is important for achieving the dual goals of change and re-usability. A lot of the criticisms of the Singleton have been summarized by Scott Densmore and on the Flash-Focus blog, and my intention is not to improve on their comments. Rather, I’d like to use the general comments by them and others to focus on good practices and re-focus the discussion of design patterns to the key issues important to OOP and design patterns. That focus, I believe, is the relationship between objects.

Dependencies Hamper Change

A core principle in design patterns is to reduce dependencies. A primary culprit in creating dependencies is the global variable. Global variables can run through a program like a skin-eating virus. One little change requires unzipping the whole package and changing all of the parts—rewriting the program. That’s why private variables and functions are so important. The little buggers are encapsulated and won’t run amok and change or get changed by unwanted operations in the program. Global variables, while making life simpler in the short run, cause headaches when even little changes have to be made. The extent to which Singletons provide a global access point, they serve many of the same functions and generate the same kind of problems as global variables. However, they often hide their global character and untangling unwanted dependencies because of Singletons is often more troublesome than the same process with global variables. You don’t expect Singletons to create dependencies and so they may be overlooked as the source of the problem. Creating global variables, on the other hand, is an act that programmers actually have to think about and so should be well known when dependency problems arise. As such they are (or should be) the immediate suspects. Not so with Singletons. After all, the Singleton structure is a design pattern and we all expect design patterns to have the opposite effect and automatically reduce dependencies. However, Singletons may have been denizens of the Dark Side all along, and we just never noticed. (Miško Hevery’s blog post, Singletons are Pathological Liars is another interesting take on why Singletons are nothing more than global variables.)

The Single Responsibility Rule

A fundamental principle in OOP is that each class (or element) should have a single responsibility. Chandima lays it out nicely in the MVC chapter in our book (p.443),

…each element in the MVC adheres to the single responsibility principle. Each element has a well-defined role. The model manages state, the view represents state, and the controller handles user input. This allows each element to be swapped out without affecting other elements.

Now you may be thinking—That’s exactly what a Singleton does! Its single purpose is to provide a single entry point. Well, not according to Scott Densmore. The Singleton provides both a single entry point, and it also insures only a single instance of the class will be created. Count ‘em. That’s two responsibilities. Well maybe so, and maybe not. According to the Freemans (authors of Head First Design Patterns), a single responsibility refers to a design principle,

A class should have only one reason to change.

Okay, but does the Singleton have any reason to change? A responsibility is a reason to change, and so yes, as a matter of fact, it does. Unfortunately, it has more than one.

The Chain of Responsibility pattern discussed on this blog is one of the best examples of the rule of Single Responsibility. Each element in the chain has one and only one responsibility. Figure 1 illustrates how the chain works. A request is passed to the first element in the chain, and if can handle the request, it does. If not it passes it on to the next element or until it runs out of options or is handled by a residual class.

Figure 1: Each element has a single responsibility.

In some respects the Chain of Responsibility pattern represents a microcosm of the Single Responsibility rule. You can see clearly what each element’s responsibility is and whether it can handle the request or not. Likewise, you can change the elements without having to change the rest of the program. All programs should have the feature of Single Responsibility.

No Tight Coupling Please

The principle of Loose Coupling is so ubiquitous in both design pattern and OOP architecture that to mention it may seem to be an overstatement. However, I’ve seen too many instances where a perfectly good design pattern is ruined because the developer willy-nilly tightly coupled objects without really thinking through the consequences. During testing, especially unit testing, these tightly coupled structures make testing alternative implementations virtually impossible without re-writing all the code. That defeats the purpose of OOP and the whole concept of encapsulation.

Singletons type to the exact type of the Singleton object. Of course with that you have no loose coupling; just the opposite. If you think this is a minor matter, tools exist for detecting Singletons (in Java) so that they don’t mess up the program. In other words, Singletons are treated like viruses. At Google, in their Guide: Writing Testable Code one of the flaws includes adding or using singletons.

Why So Many Singletons?

Several years ago I was working on a beta for a Web development tool. Like all betas, we had a diverse international group of developers and designers tweaking and testing the application. In the beta forum one of the designer/developers commented that he once had a client who insisted that he use Front Page to develop a site he wanted. When the designer balked, the client explained that Front Page was the most common tool in Web development and so must be the best. It seems that some have applied the same logic to the Singleton. Not only is it common, it is simple to write—even without private class constructors in ActionScript 3.0. In good faith, many developers seem to have concluded that using the Singleton would guarantee that their code was design pattern based and promoted good OOP. Unfortunately, it seems that the opposite may be true. So before plopping another Singleton into your code, keep in mind that you may be inadvertently adding what amounts to an OOP virus to your project.

The following diagram was added in response to Gavin’s comment that follow this post.

  1. aYo
    November 26, 2008 at 6:10 am | #1

    Well written Bill. Very well researched too. I’ll be looking deeply at my Singletons from now on.

  2. November 26, 2008 at 9:49 am | #2

    Hi Bill,

    There’s a common scenario that I’d appreciate to hear your thoughts.
    That is the loader/loadee pattern which you usually load data and pass on to the loadee. You could define a ‘setData’ method in Loadeed but you couldn’t use it on Loader in order to avoid typing (to ensure that Loader is smaller as possible).

    In that case I end up using a Singleton instance of a “DataHolder” class. Of course it’s basicly an data repository with any other responsabilities but it makes my Loadee depends on it.

    Anyway. I think that’s a reasonable choice in that case.


  3. November 26, 2008 at 9:56 am | #3

    As a programmer – the goal is to code solutions… which may require improvement and revision. From the context of your post, I get the feeling that it would be wise to touch on why private constructors were excluded from ActionScript 3.0.–_on_the_l.html

    From a practical point of view… a carpenters value is directly proportional to the quantity and quality of his tools. Wither or not he is skilled in using them is another issue all together.

    The singleton is a tool in the programmers toolbox… and when used wisely and with skill – it can solve a host of problems. To be absolutely fair one must read all of these linked posts with a grain of salt as ActionScript 3.0 injects free radicals into the equation that dramatically affect the scope of the argument.

    As an example, you haven’t mentioned any of the important caveats related to Singletons in ActionScript: i.e. modules can break singletons, marshal plan injects sub-application contexts which break singletons, improper singleton constructs guarantee failure, and etc. Rather than focusing on ‘it’s bad’ – I would think some examples showing improper use and then a proper execution would be extremely valuable and would address the root cause of the singleton debacle – inexperience in proper execution. Globally visible ‘stuffs’ don’t have to be bad: BrowserManager, SystemManager, etc.

    With regard to coupling… contracts protect interests. In development, coupling, is a continuum that is expressed throughout the application in degrees. To describe it as ‘bad’ or ‘good’ isn’t a fair treatment. Again… to focus on the root cause – inexperience in execution.

  4. November 26, 2008 at 10:57 am | #4

    Frankly, I disagree with your assertations regarding the use of Singleton.

    In my opinion, Singletons certainly have their place, when designed (and implemented, if someone is coding to an implementation rather than an interface) properly.

    I like to remain as platform and language agnostic when approaching my software engineering projects, and thus my interest in OOP & design patterns. One of my favorite projects is PureMVC, and I’m curious to hear whether or not Singleton is used to any benefit in the various PureMVC offerings. If not, perhaps you could propose alternate approaches that would provide a measurable benefit.

    At any rate, thanks for writing the article. It’s always fun to talk about these things. I respect your opinion, I’m just not sure I agree with or understand it entirely.

    Do you think Singletons are arbitrarily and absolutely wrong?

  5. gropapa
    November 26, 2008 at 1:07 pm | #5

    hi there, very interesting article indeed, but I must admit i deeply agree with Rick Winscot.
    I don’t use Singleton just to say “well ok it is a Singleton so it is a good OOP develoment”.
    In the other hand, as you say, Singleton is no more than just a global variable whiwh can be very usefull. Imagine i cannot use the singleton anymore, it could be a big pain in the ass just to pass the reference of this unique instance throughout all my objects to the final one which trully uses it…
    so maybe it not a good OOP practice…but it is very practical indeed (sorry for my english)

  6. November 26, 2008 at 1:19 pm | #6

    Hi Saulo,

    Is the ‘DataHolder’ a temporary class that holds the data to empty the loader prior to passing it on to the loadee? I suppose you could justify a Singleton in that context–you just want a single instance of the DataHolder. However, I don’t see how that solves anything and may end up with the problems Singletons bring with them.

    Have you looked at some other design pattern? Anyway, I can understand your reasoning, but do you really need to put it in a Singleton? What other options do you have?

    Kindest regards,

  7. November 26, 2008 at 1:38 pm | #7

    Hi Rick,

    I guess for me the issue in the case of the Singleton is not so much knowing how to use a tool as it is whether the tool belongs in the toolbox. After mulling over the issues raised by seriously bright programmers (and two and a half years is a lot of mulling), I came to the conclusion that I didn’t want Singletons in my programs–or in the toolbox. I suppose we could find the ‘perfect spot’ for a Singleton somewhere in programming, but I do not believe it’s worth trying to fit it in and risk the problems that accompany the Singleton.

    However, I do appreciate your wonderfully thoughtful comment and reasoning.

    Kindest regards,

  8. November 26, 2008 at 2:15 pm | #8

    Hi gropapa,

    I don’t know what language you speak, but your message is quite clear in English. No need to apologize, and I am certain it is better than I could do in your language!

    Con mucho gusto,

  9. James
    November 26, 2008 at 4:30 pm | #9

    I had a discussion last Friday over beers on this same issue. I do not believe singletons should be used when they can be avoided. Generally they are a sign of laziness. A programmer doesn’t want to correctly associate two instances and instead makes one of them Global.

    In my experience 90% of the problems singletons are purported to solve can better be handled using event handlers and callbacks.

    Where I have found them useful is in cases where Aspect Programming would be useful. Loggers and debug code including instrumentation. These are cases where there is no actual association between the code and the singleton – it merely serves a meta-utility function. It’s nice to drop a singleton into code in those cases to check something out without having to alter several classes to pass an instance down the constructor stack.

  10. November 26, 2008 at 4:42 pm | #10

    Hi Caleb,

    Do I think Singletons are arbitrarily and absolutely wrong? I wouldn’t put it that way, but yeah, that’s pretty much it. More accurately, I think that Singletons violate several important OOP and design pattern dictums. Those dictums listed in my post are only those that I took to be the most important, but others have been cited as well.

    For the longest time I simply assumed that Singletons were misused in places and raised a hubbub among cranky purist who spend less time in real world and more time contemplating their navels. However, most of those who were raising a fuss were practicing real world programmers who kept running into problems when Singletons were used. When I learned that Google’s programming manual listed Singletons as something NOT to allow in their programs and even created a “Singleton Detector” to find and rid programs of them, I became more concerned. I found the materials that I put in the post to substantiate the case against Singletons because I think they’re important.

    As for disagreeing with me, that’s fine. (Besides, I’m married and am used to it.) The first time I was confronted with serious questions about the validity of the Singleton, my reaction was the same as yours. But I’ve had a couple of years to think about it and the host of problems with the Singleton, especially in larger programs led me to the conclusions I reached. Take a look at Miško Hevery’s article and the Google guide for writing testable code, and you’ll have more food for thought.

    Kindest regards,

  11. ike
    November 27, 2008 at 2:07 am | #11

    I have actually not done any work yet with AS3. What strikes me about this article however is that, although you’ve provided a lot of support for your argument in the form of other people agreeing with you, you’ve not really provided any thorough example of your arguments against using singletons. You’ve suggested that they couple the application and that it would lead to small changes having big rippling effects making the application harder to modify and maintain… but there aren’t any examples of how that might actually happen and what makes that different from (or less likely than) similar ripples caused in non-singleton objects.

    Also, at least in the ColdFusion code that I write, the responsibility of creating only one instance of a given class doesn’t generally belong to the singleton, it belongs to the IoC factory that creates it. As a matter of fact, I can’t even imagine the scenario in which the class itself would be capable of ensuring that it has only one instance. You need a named lock around its creation to ensure that, and that can only happen outside the class. Is that not the case in AS3?

  12. November 27, 2008 at 4:46 am | #12

    Hi James,

    I wouldn’t say that the root cause of using Singletons is laziness, but I applaud your method of working out these knotty problems over a beer!

    One other issue that we may need to clarify is the difference between a Singleton (design pattern — with uppercase ‘S’) and a singleton (class instance with lowercase ‘s’). My doubts about a Singleton pertain only to the design pattern and have nothing to do with a singleton that is a single instance of a class in a program.


  13. November 27, 2008 at 5:04 am | #13

    Greetings Ike,

    You’re right, I didn’t provide an example of a Singleton screwing up a program. I wanted to focus on the OO issues, especially the ‘rules’ of working out relationships between objects. Besides, the links I provided had tons of examples, including a video and a 57 page PowerPoint presentation showing exactly how the Singleton will ruin your day. See:

    The author, now at Google, formerly was a developer for Adobe. (We’re all in the same big dysfunctional family!)

    As for citing only those who agree with me, the first three links on the post were to AS3 developers who certainly didn’t find the Singleton bad. In fact I suppose at some level you could say I disagreed with them all. However, I believe you’re absolutely right that we need to air more than one side of an issue, and it’s valuable readers who send in comments that do just that. As you may have noticed, most of the comments are hardly in agreement. I’m especially happy to find visitors from other languages like ColdFusion.

    Take care,

  14. November 28, 2008 at 8:36 am | #14

    I read your post and is was pretty clear to me. I’m still learning to best practise OOP programming in AS2 and AS3. more and more AS3 because you (read I) certainly have to program OOP in AS3.

    In AS2 I used singletons some times. Mostly for manager classes which you then could call from any other class. The explanation that this works the same as global variables explains it best.

    I then searched for example classes of how to set up a manager class without the singleton pattern. Unfortunately I didn’t find one to do the explaining job satisfying.

    What would your advice be?

  15. November 28, 2008 at 10:07 am | #15

    Very good read. I’ve never thought about it before, but your reasoning, and the facts presented in the other linked articles makes perfect sense. I often use one singleton in most large applications to manage the current state, but that definitely has a large coupling effect.Good food for thought, thanks!

  16. November 29, 2008 at 3:20 am | #16

    Hi Arjan,

    Don’t feel bad about still learning best practices in OOP. As soon as I stop learning, it’s not going to be fun any more. (And I plan on a lot more fun!)

    Many developers have the same question that you have: If not a Singleton, then what? Miško Hevery has a good article on that question and provides answers. Take a look at:

    It doesn’t specifically address a manager class, but it does address similar issues.

    Take care,

  17. November 29, 2008 at 3:35 am | #17

    Hi Tyler,

    I suppose it’s easier to think of using global variables instead of a Singleton. Had I suggested we never use global variables, I doubt that anyone would have cared. It would be one of those tell us something we don’t know reactions. Because the Singleton is a global variable wrapped in a design pattern, we tend to get riled up.

    I’m glad the post makes sense to you. Thanks for participating in the discussion.

    Kindest regards,

  18. December 4, 2008 at 8:53 am | #18


    Excellent article.

    I decided not to use Singletons a while back due to the inelegance and all the attached problems these AS3 “workarounds” create. But I had still not entirely made up my mind about them and probably would have gone back to trying to use them again.

    Frankly, it’s a load off my mind to get some very solid reasons as to why not to use them — with the static variables simile being the solid rock at the core of your argument, IMO.

    Thanks for sharing.

  19. December 4, 2008 at 11:39 am | #19

    Hi Nick,

    I’m glad to hear the post was helpful. Right now I’m working on the Visitor pattern, and it is a nice return to a pattern that is very helpful and intriguing at the same time.

    Take care,

  20. Gavin
    December 5, 2008 at 4:36 am | #20

    I am still not clear on what the alternative is to a singleton. You could use statics but that makes the problem even worse because you can inherit/override a singleton’s members. What implications does this have for something like the facade? Also a domain wide single point of entry and not responsible for state, a singleton feels like the logical choice here … I am still confused as to exactly why this is bad and I see it impacting greatly on how we should approach GoF based patterns in general. What are your thoughts on this?

  21. December 5, 2008 at 2:04 pm | #21

    Hi Gavin,

    The design patterns in GoF hardly hang on the Singleton. (Keep in mind that ‘singleton’ is a single instance of a class (no problem), and ‘Singleton’ is the design pattern.) Assuming that you’re referring to the Singleton design pattern, the problem centers around the global nature of the design as noted.

    Rather than using the Singleton, my key focus is on the Client. Some of the design patterns include the Client as part of the design and others include it as implied (such as the Visitor which I’m currently working on.) Still others give no clue in the class diagram where the Client sends initial requests. However, for me the key connection is the relationship between the Client and the design pattern and a Singleton simply causes problem. I’ve added a diagram at the bottom on the original post to show my thinking on the issue.

    Thank you for bringing up this issue. It was one of the many that led to my own head scratching concerning the Singleton.

    Kindest regards,

  1. December 5, 2008 at 8:07 am | #1
  2. February 26, 2009 at 9:48 pm | #2
  3. March 24, 2009 at 5:11 am | #3

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>