Singletons

I’ve been playing about with a code base that has a large number of singletons, for what appears to be no apparent reason.
Something about singletons doesn’t sit quite right with me, but in the most part, if they’re not misbehaving, I’ll probably leave them be.

The thing that bothers me a lot more though, is the fact that everyone else is forced to know about your singleton-ness..

ImASingleton.getInstance().doSomething();

*shivers*

If you have to store global state, it would be nice if we could hide that from the clients. Why do we have a single instance with instance variables accessed through a static getInstance method, when we could hide (ooh, encapsulation) the implementation behind multiple instances with private static variables?
By using instance methods, we also get all the interface / testing / mocking goodness.

new ImASingletonButYouCantTell().doSomething();

OK, I’m rambling… am I missing something? (please rant below)

2 thoughts on “Singletons”

  1. The majority of Singletons I’ve seen were disguised global variables. I’ve rambled on this previously as part of a post on a specific refactoring task.

    It’s a problem with Java like languages that want to make everything into a class. The focus of the language should be on objects and not on classes. So, all in all I consider that singletonitis is a problem of some languages.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>