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?"

1 comment:

Anonymous said...

A better question is, how much overhead does creating a second instance of this object and/or how many resources (memory most likely) does having a second use up? Singletons shine by preventing un-needed code execution and resources ever getting used/allocated and signifies to other developers looking at your code that you would prefer there only be one instance of this type of object at runtime.