The best way to teach is to start with something simple. As far as design patterns go, the singleton pattern may be the simplest one. The article on 5 reasons why you should love design patterns
used the singleton as an example. The article received valuable feedback from our readers some of which included;
My advice is to avoid using the Singleton pattern in your software design.
Other developers are on record saying the singleton is an anti-pattern. So what is it about the singleton that makes it synonymous with the word evil when designers talk about design patterns? The reasons below will help us answer this question.
Reasons why you should avoid using the singleton by all means
- Global states- check this link for more details
- Hidden dependencies – check this link for more details
- Less testable – check this link for more details
- Less maintainable
- Tight coupling
The above list is not exhaustive; it lists only the commonly given reasons.
Here is my personal opinion, I do not believe in absolute evils. In as much as we would want to be just, sometimes we have to temper justice with mercy
When faced with configuration files, logging or database connections, I say the singleton is a lesser evil than not having it at all and opening multiple database connections which can slow down your application performance or logging from different points. The above paragraph is not an endorsement of the singleton as a pattern
. If you can avoid them then by all means please do. Should you decided to ignore the writing on the wall and use the singleton pattern, then by all means make sure you understand and document the consequences of your decision
: Modern day applications favor loose coupling, maintainability, and most importantly automated testing. The singleton pattern goes against the above. It is for these reasons that we find the singleton pattern guilty and give it the ultimate punished.
Do not use them!