DEV Community

Discussion on: Why Singletons Are Bad?

Collapse
 
jwp profile image
John Peters

Singletons do not violate SRP except when poorly designed. They are a perfect pattern when needed. The are used to obtain adressibility, to an object often with functions,methods or properties pertaining to the object name which describes the responsibility.

There are other patterns which work as well, in particular events and event handlers. If the event definition is static then the ability is similar to a singleton.

In Javascript, the function, a true first class citizen which diminishes the need for singletons.

Finally, observables which are extensions of the event pattern may be static too. Event bus design often use this pub/sub pattern also diminishing the need for the singleton

All work, all are good so design wisely and there won't be any issues.

Collapse
 
amrtaher1234 profile image
Amr Mohamed

I totally agree with you, they could be perfect in such use cases but I generally would not recommend the using of such pattern. It just doesn't feel right to have something globally swimming in your codebase and you'd have to design it carefully to take care of your unit tests and to disallow other functions or classes to manipulate it without being authorized to.