The much dreaded Singleton

I have come across so much contempt towards the Singleton, it’s almost scary. Singletons are crucified all over the place, and whilst there are very sound theoretical reasons to avoid abusing the pattern, the Singleton has a healthy place in ui programming.

More often than not development for Flash puts us against unique instances of things. Usually, this happens in the context of UI programming: a single stage, a single mouse, etc. Some aspects of many applications are also better off built centralised, for sometimes one simply wants to avoid two objects performing clashing updates on something (a good example is animation of gui components and overwriting of property interpolation tasks in tweening engines). In such situations, one who blindly aims to avoid building a Singleton most probably ends up isolating the shared state needed to sync the instances in static vars and methods, achieving (in the best case) something that looks more or less like a Borg design. New catchy notions, same old enemy – global state.

Speedy

This has nothing to do with loose coupling or design patterns, but a Singleton is usually a better alternative to static vars and methods for at least one big reason. Static stuff in Actionscript is very slow to access. (What was it, 10 times slower?) A call to a method on a singleton will make use of one static var lookup – the reference to the singleton – and that only if a reference to the object is not already locally available. The same method, if declared static, will probably have to access at least one more static variable in order to read and write global stuff. [EDIT: This is not entirely correct, see the follow-up benchmark on static access performance.]

It seems that in Python sharing state among instances is considered more elegant than using Singletons. One could easily extend the same logic to Actionscript: more transparent code, good-looking instantiation with new, etc. Still, if more than one static var is to be accessed during method execution on such objects, or if the objects are to be created and discarded on a usual basis, performance-wise, Singletons will most likely be a faster alternative.

In this context, let me demonstrate my personal approach to implementing a Singleton:

public class Singleton
{
	public static const instance : Singleton = new Singleton ();
	public static function Singleton ()
	{
		if ( instance ) throw new Error ( "Already instantiated." );
	}
}

My trick looks like an exploit and a generally terrible idea (now how could a constant change its value?), but works perfectly fine AND avoids the need for the additional overhead from a getInstace () method call and from accessing a private static var to return the instance.

At least some loose coupling please

Static vars and methods, shared state among instances, and Singletons are almost equally deadly to loose coupling. In all of those cases, typing and access issues hinder substitution of the class in question in code variations or upgrades.

The above is completely true, unless one decides to take the Singleton pattern a bit beyond what it usually looks like and to add a layer of abstraction:

public class AbstractSingleton
{
	private static var instance : AbstractSingleton;
	public static function getInstance () : AbstractSingleton
	{
		if ( !instance ) throw new Error ( "Not instantiated." );
		return instance;
	}
	public function AbstractSingleton ()
	{
		if ( instance ) throw new Error ( "Already instantiated." );
		instance = this;
	}
	public function abstractMethod ( ... ) : *
	{
		//	to be overriden.
	}
	...
}

If used as intended this should do the trick. One could probably do a few things to strengthen the implementation, preventing instantiation of the abstract class, even adding some sort of auto-instantiation try-catch trick for the child classes, and so on and so forth. What’s important however is that this ‘abstract’ Singleton pseudo-pattern provides freedom in chosing which concrete object to instantiate at app start, and that’s already quite a gain in terms of loose-coupling.

Singletons can be rather healthy in a UI context

Again, Singletons are a good thing in the context of gui programming. All voluminous and immutable objects are healthy candidates for becoming part of the global state; a provider for a huge and static bitmap is a great example, also an audio mixer for button noises and ambient loops illustrates the point, for there is an absolute benefit of keeping those globally accessible and limit them to a single instance – there is a guarantee that the underlying bulky resource will be loaded only once in the memory.

Also, when an application relies heavily on client/server interactions, and when these put ui-responsiveness at stake, a globally accessible remoting service, be it static, Singleton or Borg, will enable the programme to centrally cache repetitive interactions’ results.

An edit to my boring conclusion

Instead of my previous empty conclusion, I’ll post someday an example of how one could actually get unmatchable loose coupling with the help of a Singleton registry for services.

Bookmark and Share

5 Responses to “The much dreaded Singleton”


  • Hi Hristo,

    I like your post on Singletons even though I’ve quit using them, and I don’t believe that they’ve suffered the martyrdom you suggest.(They deserve to be kicked around a lot more!) The fact that you have thought about them and their advantages and limitations puts you way beyond most developers.

    Miško Hevery’s post Singletons are Pathological Liars is one of the best explanations of why to avoid Singletons—they act like global variables and break encapsulation. Of course people love and use Singletons, and that is the very reason they’re so dangerous. It’s almost like placing a virus in your own code.

    One alternative to Singletons is simply to use the Client as your entry point. Many design patterns include the placement of the Client module in the class diagram (implied or as an integral part of the pattern) along with the kind of reference to the different modules. Some references are to a single module and others, like the Abstract Factory, are multiple and complex. However, what they all have in common is that they maintain the integrity of the components and keep the design open for re-use and update.

    Let’s keep this discussion going.

    Kindest regards,
    Bill

  • Hey Bill,

    Miško Hevery’s series of posts on Singletons are indeed a great read, which I have come across before, I believe, from links on your blog.
    I will soon come back to this topic with a practical example that we can discuss throughout. Thank you for the reply!

  • I’m interested in this – what proof is there that accessing static variables is 10 times slower to access?

  • I’ll post about this, results are insanely divergent among players.
    EDIT: Done.

  • I too have been a fan of Hevery for a while. I was looking forward to gaining deeper understanding of his concepts as I implemented true unit testing and moved toward continuous integration in a Flex project… and the project was abruptly cancelled. All interesting stuff, but left to my own devices I tend to get more into geometric programming.

Leave a Reply