Rehabilitating the Singleton Pattern
Join the DZone community and get the full member experience.Join For Free
“design patterns: elements of reusable object-oriented software” came out in 1994 and it changed the software engineering landscape. what made this book unique is that it wasn’t really based on code (although it did contain a decent amount of it) but on terminology. it picked up general ideas and concepts, captured them in diagrams and, most importantly, gave them a name.
the power of names
nobody had really thought about doing that before, and the idea was so good that even today, fifteen years later, most of these names are still in common use. you won’t come across a developer who has never heard about singleton, a visitor, a factory or a façade.
of course, the science of software engineering has advanced quite a bit since 1994, and some of the concepts explained in the book came under attack. for example, we know a lot more about testing now, and this past decade has allowed us to identify techniques that make testing easier, and also anti-patterns that tend to get in the way of making our code testable.
of all the design patterns from the book that have been criticized, none has taken as much of a beating as the singleton. not a day goes by without reading in blogs or irc that “singletons are evil” and that you should avoid them at all costs. what’s surprising is that i read this coming from senior developers, and this statement tends to deeply puzzle more junior developers who suddenly find themselves having to rewrite a piece of code that they thought was quite natural and officially acknowledged as a good coding practice.
here is the truth:
singletons are fine as long as you don’t implement them with static
scoping it out
let’s take a closer look at this statement.
singletons are very natural entities in a software engineering. regardless of the kind of code you write (front end, back end, embedded in a browser, running in a container, etc…), you will most likely need to talk to certain services that only need to exist as a single instance. it’s also no surprise that popular dependency injection frameworks such as guice and spring explicitly support the singleton pattern.
don’t feel bad for feeling the need to implement a certain concept as a singleton, it’s perfectly natural.
so what’s wrong with statics?
there is ample documentation on the problems that static variables and methods (but mostly variables) cause, but in nutshell, they make testing and concurrency more challenging, and as such, they should be avoided. the main problem is that static defines a scope that’s even bigger than the application itself. it’s a state that will only disappear once the class that contains it gets unloaded, so frameworks have very little room to control its life cycle. another way to look at it is that the static scope is beyond the reach of java programs and lives in the realm of the jvm.
this is really the only problem. if we can find ways to have singletons that are more narrowly scoped, then the concerns i mentioned above disappear.
the next smaller scope to the one that static provides is instance: the value will remain live as long as someone is holding on to a reference to the object, but once that is no longer the case, this value is gone.
one way to improve on the static scope would be to create all your singletons in your main method and then pass them down to your application. with this change alone, you have suddenly made your entire application much easier to test and easier to reason about from a concurrent stand point.
once you start going down that path, you start wondering if this “main” scope isn’t too broad. if a singleton you create in your main method is not needed until way further down the stack frames, maybe there is no point in exposing that singleton to your entire application. is there any way that you could either create (ideal case) or at least expose (second best case) that singleton only to the section of your code that needs it?
this code structure also rises another question: it’s not exactly convenient to create a bunch of singletons in your main method and then pass them “down”. how do you do that, anyway? ideally, you pass them as parameters to the methods you are calling, but that is not going to scale very well, never mind the fact that your method signatures are going to start looking like monsters. updating your entire call chain whenever you need access to a new singleton is an absolute disaster since you will have to add this parameter to the signature of each method.
one way to mitigate this problem is to group all your singletons in one class called, say, configuration, and only pass that class around. if ever you need one more singleton down the road, you just add it to this class and you don’t need to change any method signature. that’s better.
we are still exposing a lot of code to all these singletons, though, and even that uber configuration parameter looks like extra weight on these methods (most of which might just pass them around and not even use them).
injecting for fun and profit
this is where the @inject annotation comes in. initially popularized by guice, this annotation ended up being promoted to a standard by jsr 330: “dependency injection for java “. i’m not going to go into details on how to use this annotation (check out guice’s excellent documentation ), but i’ll just limit my comments to the topic of this post, which is how to implement singletons properly.
using @inject to gain access to your singletons solves the following problems:
- no static.
- the creation of the singleton is externalized. you don’t need to worry how or where that singleton is created, you just need to specify that you need it.
- finer scope. only the class that you declare this injected field in will have access to that singleton. a side benefit of this is that you no longer need to pollute all your method signatures in order to pass this singleton all the way down the stack frames. it’s declared as a field and the dependency injection will automatically assign it at start up time.
- finer granularity. you no longer need to pass a monster configuration object that contains all your singletons around: just specify which singletons you need exactly.
this post is getting a bit long already so i’ll stop for now. there is much more to cover on the subject of singletons and, more broadly, of dependency injection, which i’ll try to cover in a future post.
in the meantime, let’s all agree to acknowledge that when implemented and used properly, the singleton is a very useful design pattern.
Opinions expressed by DZone contributors are their own.