+1

Does the Singleton really violate the Single Responsibility Principle?

Daniel Li 2 роки тому оновлено Smits Code 2 роки тому 2

On the Singleton page, it says:

The Singleton pattern solves two problems at the same time, violating the Single Responsibility Principle

This view is echoed by the article Why Singletons are Evil, which writes:

2) Singletons allow you to limit creation of your objects.

This is true, but now you are mixing two different responsibilities into the same class, which is a violation of the Single Responsibility Principle.
A class should not care whether or not it is a singleton. It should be
concerned with its business responsibilities only. If you want to limit
the ability to instantiate some class, create a factory or builder
object that encapsulates creation, and in there, limit creation as you
wish. Now the responsibilities of creation are partitioned away from the
responsibilities of the business entity.

However, I don't think singletons violates the Single Responsibility Principle (SRP).

As clarified on the The Single Responsibility Principle article, the Single Responsibility Principle is "about people", and "responsibility" defined as a (business) "reason for change". A reason that the code for accessing the database may change is if the type of database use changes, but having a single pool of connections (enforced by the singleton) and making it available is, to my understanding, two separate technical requirements but a single business responsibility.

Would love to know your thoughts!

Hi Daniel!

Thank you for asking!

1. Yes, I think it indeed violates SRP because both of these features can be implemented independently (at least, in many OOP languages).

2. Practically speaking, I personally don't care that much about following SRP. To me, SRP is just one of the indicators of the design. Still, as an author, I can't ignore this issue completely because I'd get backfire from the opposite camp. In any case, if I could do my thing efficiently while violating SRP, I would definitely do it. If it bites me in the future, I will refactor it away.

BTW, if anyone reading this topic wants to add something to the discussion, you're very welcome!

I believe that people more experienced than me are right in this regard. But I also want to point out that we must live in a practical world and let go of some things to make our lives easier. If you are writing a small PHP website and want to manage DB connection in your application, it is better to use Singleton than writing two classes. It decreases the complexity in the small-scope application but increases it in larger applications. Really most of the choices you make are today vs. tomorrow in this. Singletons are at least better than Global variables in that regard.