Sunday, February 8, 2009

Singleton Pattern

I am not a fan of the singleton pattern. This may come as a surprise to some, as the very first thing that people may see when using my code is the wrapper I have for my IOC container acts as a singleton.

So why do I, along with many others, not like the singleton? Because it is usually used incorrectly and hard to test.

The first time I had seen massive singleton abuse was when I had to go on a consulting gig to help "finish" a project, i.e. the final sprint prior to go live. The whole data access layer was made up of a mess of singletons. There was no need for it, none for the objects had state let alone required to hold state in a single instance but they would not let us, the hired consultants, refactor it out. Bizarre*. Since then I have seen a singleton butcher-job at just about every contract I have had. it seems to be the first pattern people use and the first to be abused.

So when do i use a singleton? Well when an object that should only have one instance. The notion of singleton implies there is only one logical possible instance of that type that can be in creation at a time. I think this is the fundamental problem I regularly see. Most times I see the use of a singleton this is just not the case.

To highlight this even more, often the object itself does not even have state. If the type has no possible (instance) state, then there is surely no need for singular state! This is the time where the object is just a static class. In the same way it is ok to use singletons, it is ok to use static classes, just make sure it is the right circumstances for your choice.

One annoyance is when singletons are used so they can be "thread safe" and then the construction of the object is not thread safe. please investigate how to do this if this is actually a concern. Even better use an IoC container! By using an IoC the object becomes easily testable and you infrastructure concerns are hidden from the consumer. To me, this is a good thing. :)

*That project is still going, still not live and apparently still has singletons used inappropriately in the data access layer. Oh well.

No comments: