How to Decontaminate a Singleton




For about three years now there’s a debate about using the Singleton pattern. Some call it evil, anti-pattern, and the like. If you have a look at the Gang of Four (GoF) patterns you’ve to realize that they are still present in the community, even more than 10 years after first publishing of the book. Patterns are commodity and the grandmasters can’t be wrong with their invention, you may think.

It’s not easy to kill a pattern like the Singleton.

I don’t know if we really have to, but it seems that we have to analyze every case we tend to use one. Experience show that in the beginning everything is crystal clear, but in the end you’ve a smell in your design. Singleton is easy to use, but not as easy to understand in context of design.

With unit testing, dependency injection containers, etc. the number of useful contexts and the necessity for a Singleton tends to zero. If you have a look at Spring, e.g., the Dependency Injection (DI) container decides itself in which context it needs a Singleton. So, by default you don’t have to think about to create one on your own. DI delivers a new concept that helps to cope with the problems a Singleton was intended for in the past.

Singleton are a key concept in J2EE environments based on EJB 2.x. So, we have to live with Singleton-based design smells for the next years. Although, DI concepts conquer the Java land quickly. So, it’s clear that both concepts have to be combined in meantime.

Here’s a suggestion that may can help in Spring contexts:

Define a Spring bean for each Singleton you use. For new DI-like implementations use the Spring bean as a wrapper that allows to access the functionality of the Singleton. The old code needs no adaptations until you start to refactor it. The new code uses the Singleton functionality like expected from a POJO-like implementation through the wrapper.

With the wrapper implementation you will start the first step in refactoring the Singleton functionality. This will be the base for later refactorings of the already existing code. In the end the original singleton implementation can be refactored and transformed into the wrapper to get a “real” Spring bean implementation.

Besides the advantages you’ll get with introduction of DI you decouple your old design, unhide dependencies and get the possibility to visualize and document them. The application context files, Spring uses for the declaration of injections, are the foundation to do that. The Eclipse SpringIDE plugin, e.g., can create a diagram of such dependencies.

Further reading:

Friends Don’t Let Friends Write Singletons
Why Singletons are Evil
Perils of the Singleton

  • martinkrischik

    In the SCJD exam you are not allowed to use Swing. Any ideas on how to replace the ever so evil singleton with bare metal J2SE?