DEV Community

Discussion on: Why Singletons Are Bad?

Collapse
 
amrtaher1234 profile image
Amr Mohamed

Thanks a lot for your reply :D

Actually there is a workaround on how to create singletons on multithreaded environments, you can change the getInstance function to be synchronized so multiple threaeds wont access it simultaneously.

The Dependency Inversion Principle states that the high-level policy of your system should not depend on low-level details. Also, abstractions should never depend on details. When we generally create singletons we attempt to write a global object that encapsulates the low-detail logic instead of the high-level business logic.

Also in the Open/Closed principle whenever you want to change the behaviour of the singleton you will have to change the class itself, lets take an example.

Say your singleton was a class that calculates the areas of multiple shapes ( Square / Rectangle )
If for example you needed to add a newer shape to your calculations you will now modify the calculate function inside your singleton.
This is a fairly simple case but you could think about other usecases in that matter and I could somehow agree that it does not violate the Dependency Inversion Principle in its design but in most codebases that is used in it does.