Singleton Madness

I’ve been spending the last few weeks trying to exorcise a pesky singleton class from EP Simulator. This is the Options class, which contains all the program options that are saved from session to session. There is only one set of Options, so I had naively made the class a singleton. Singletons being what they are, the class soon started infiltrating many other classes, sitting there as a hidden dependency, rendering classes untestable, and generally causing trouble. Having read such posts as Singleton Considered Stupid I realized the error of my ways and I have been diligently trying to exterminate the nasty thing. It’s not easy! The concept behind a singleton seems worthwhile: you only want one instance of the object. So what do you do instead of making a singleton? Just create one instance of the object! Make sure you just are using the same instance throughout your program and it can be an ordinary class, which you can then subclass to create mock classes for unit testing, and which you just pass around as needed to your objects, making the dependency explicit. Don’t hide dependencies in singletons! My advice: if you have singletons mixed into your code, the sooner you remove them, the better. Right now I am tearing the code apart to eliminate the nasty singleton, breaking code right and left, but I know the results will be worth it, eventually.

By mannd

I am a retired cardiac electrophysiologist who has worked both in private practice in Louisville, Kentucky and as a Professor of Medicine at the University of Colorado in Denver. I am interested not only in medicine, but also in computer programming, music, science fiction, fantasy, 30s pulp literature, and a whole lot more.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.