<= Home
Singleton Overuse Disclaimer
I’ll admit that I was very guilty of overusing the singleton. Joshua Kerievsky coined the phrase “Singletonitis” meaning “addiction to the Signleton pattern”. I had a severe case of it but I have seen the light. Many refer to the Singleton as an antipattern (a bad solution to a problem).
For those that do not know what the singleton is; it’s a pattern to ensure only one instance of class exists in the system. It is well known class and therefore acts as global data. First global data is just bad. (That’s why I am against arbitrary static members too). Martin Fowler said it best in PEAA “global data is guilty until proven innocent”.
I’ve composed a list of frequent reasons it is misused. This list is by no means complete so please feel free to contact me when you discover other incidents of abuse of the singleton so I can add it.
Simplify Method Signatures
We all hate methods containing a huge list of parameters to pass in. It’s easier to put those values in a singleton and request them when needed. This is bad though in most cases. Making your data global will make it hard to debug and cause many unexpected errors even in the simplest cases. We have all sorts of nice protection mechanisms in .net for our classes, we don’t want to break that by "Singletoning" them.
Simplify Method Signatures (part 2)
Lets say that you have a simple n-tier application; the presentation layer, business layer, and then data layer. If your data layer needs a value from the presentation layer, it's real easy to stick that value in a singleton so that you don’t have to pass it through the business layer. Again this has the same negative consequences as the preceding statement.
Simplify method calls.
I already talked about bad static/shared members. Now that we aren’t' using them (right?), you have to instantiate an instance of the object to call the method. It's easier to call
SingletonClass.GetInstance().DoSomething();
then it is to do
SingletonClass sc = new SingletonClass();
sc.Dosomething()
but I’m confident many will back me up when I say laziness is not a good reason to use a singleton.
Improve Memory Performance
When developing we want to be cautious not to optimize our code until necessary. Pre-optimizing our code is a big no for an agile developer. Singleton is an excellent option for caching and other similar ideas, but make sure you don't do apply the pattern prematurely.