Archive for April, 2011

Stop Singleton Abuse!

There is a general misconception about how Singletons should be used.

Possibly, because it is true that for having global state, it is better using Singletons, than just plainly global variables or class objects. However I quite often encounter the claim that Singletons intend to provide global state. I have repeated this on numerous occasions, which is why I will put it here once and for all.

Singletons do NOT justify global state!

Some people see the Singleton as a justification for global state, along the lines of  “If there’s a pattern for it, it must be good”. Well no, it isn’t. Global state is considered harmful. For a number of reasons, that even Singleton-misuse won’t make go away, simply because:

Singletons are NOT intended to provide global state!

The Singleton is a creational pattern. It is used to enforce, that a class be instantiated only once. What it basically does is, to give control over instantiation back to the programmer. This is what you sometimes need in languages with classical constructors (Java, C++ and such).

So while Singletons are often used to replace someGlobalExpression with SomeClass.getInstance(), it is actually intended to replace new SomeClass().

It is evident, by name, that the method is supposed to return an instance. The possibility to return the same (and thus global) instance again and again, is subject to implementation. Thus using a Singleton for global access actually violates that encapsulation and unnecessarily ties clients to the implementation. And if at some point you decided to replace the implementation by a Multiton or a Pool, a lot of code could break (because the assumption that the code always returns the same instance no longer holds).

You should ultimately think of the Singleton as a special case of a Factory. Just imagine that that static getInstance-method were called createInstance. And you’ll be using it just the right way.

, , ,

Leave a comment