Say No To Singletons

| | Comments (0) | TrackBacks (0)

Admittedly, I've created a fair number of Singletons in my day. But I've moved on in recent years, and see the error of my ways.

First a quick note.

There are two flavors of Singletons. The one where you are prevented from instantiating the object and must call Foo.getInstance(). And the one where (in Java and similar ilk) all the methods on Foo are static. Yes, the two are effectively the same thing.

What I find super weird are those who mix both. That is, every static method call on the class in turn calls getInstance() and calls the corresponding instance method on the object. WTF?

Also note singleton instances usually have a global scope so any other class can fetch the (one and only) instance and use it. If the singleton isn't global or at least broad in scope, why would you wrap it as a Singleton?

Don't get me wrong, having a single instance of something is a good thing, assuming you should only ever have a single instance of it. Also many objects need to have a broad scope (a logger object for example).

It's the lazy initialization of the Singleton instance that causes issues.

By lazily initializing the object, you have to lazily initialize the configuration parameters, and the logging, and anything else this new instance requires. Then lazily configure the object, if it needs it (get jdbc params, setup connection pool, etc). This turns your application inside out.

Instead, the application should be configured and assembled. You should give objects with a global scope their configuration parameters, and then publish them for use by other objects. If there are issues with the configuration or initialization, failure happens at startup, not at some place deep inside the application, many moments, hours, or days later.

To rephrase, assemble and configure all the objects with a broad scope up front, keeping in mind the dependencies between them, then make them available through a single Singleton like registry object to the rest of the application.

For a deeper discussion on the patterns involved, see the older MF article here.

The takeaway is that you use Dependency Injection to assemble and configure your broadly scoped objects up front, and the Service Locator to allow all objects to find them.

For modern Java libraries that help you accomplish this, see:

For more, see this list of existing frameworks.

The point here is to get away from lazily initialized Singleton instances for broadly scoped service like objects. Fail fast, I say.

For a few other points on why Singletons are bad, see this article on the lonely Singleton at the PicoContainer site.

0 TrackBacks

Listed below are links to blogs that reference this entry: Say No To Singletons.

TrackBack URL for this entry: http://www.manamplified.org/cgi-bin/mt-tb.cgi/345

Leave a comment