DEV Community

Discussion on: Why Singletons Are Bad?

Collapse
 
incrementis profile image
Akin C.

Hello Sekab,

thanks for your article.
I enjoyed reading something understandable about software engineering for a change :)!

Regarding Singletons, I read in a book for game developers that it can be useful as a log file class to catch errors or the status of variables by writing them to a log file.
Nevertheless, I also read (I don't remember where) that singletons don't "work" with threads. So I agree with your statement "I believe that singletons and they have their own use cases".

Regarding the Open/Closed principle, I'm not entirely sure if that's true, because doesn't it depend on how you implement your singleton?

I also don't see how the Dependancy Inversion Principle is generally violated here, because doesn't that depend on how the relationships between your classes are structured, e.g. in the UML class diagram?

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.