Singletons: Evil or Pattern?
Are singletons evil? The current Singleton pattern wiki entry at C2 tries to make a point that, like everything that is easy to use and implement, singletons might be overused, and maybe even evil (muahahahaha!).
If you have done any interviewing you have noticed that when you ask people what patterns they are familiar with, most engineers will immediately come up with Singleton first.
This is obvious, Singleton being the first pattern most people learn when learning design patterns in any language. But most people have the following issues with singletons:
- They are typically used for two things at a time, which is not a good practice (creation and enforcing of singleness
- Too often they are used simply like global variables were used in the old days
- They are typically overused. Sometimes things are singletons when they could have been a parameter on the methods or on the constructor.
- When overused, they tend to have a negative impact on unit testing, when some code calling getInstance() on a singleton representing a service brings in services that are not needed, or worse, making it impossible for your unit tests to use mock objects or test implementations
You can read more about it on the Singleton pattern wiki entry at C2. The consensus seems to be to use the visitor pattern in such cases.
Anyhow, it's something to think about for your next refactoring..