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.
Categories