Monday, July 25, 2011

Singleton Abuse

I know this is a tired topic, but when explaining how not to abuse the singleton pattern, I explain it this way:

Many developers ask themselves this question: "Is there any reason anyone would want to have two instantiations of this class?" This is the wrong question and leads to an over-abundance of singletons. Really, they should be asking, "If I instantiate more than one object of this class, will everything break?"

An additional benefit of approaching the pattern this way is that an answer of "yes" leads to the questions, "Why would my code break? Can I refactor and generalize so that the singleton pattern won't be necessary?"