Reputation: 31
I've heard it said many times that a benefit of using Dependency Injection (DI) is that it allows/encourages/enforces the Single Responsibility Principle (SRP). I question whether that is true and would appreciate clarification, which I have not been able to find.
In my mind, the use of dependencies allows for SRP, but how those dependencies are created, whether through instantiation, injection, or some other mechanism, does nothing for SRP directly. Can some one provide an example for how using DI, either through a constructor or properties, allows/encourages/enforces SRP any more so that having the same dependencies which are created in the type initializer or constructor?
Upvotes: 2
Views: 122
Reputation: 172616
There is an interesting paragraph in (my book) Dependency Injection Principles, Practices, and Patterns that talks about the relationship between DI and the SRP:
In section 2.1.3, we described how the SRP states that every class should have a single reason to change. Violating this principle causes classes to become more complex and harder to test and maintain.
More often than not, however, it can be challenging to see whether a class has multiple reasons to change. What can help in this respect is looking at the SRP from the perspective of cohesion. Cohesion is defined as the functional relatedness of the elements of a class or module. The lower the amount of relatedness, the lower the cohesion; and the lower the cohesion, the greater the possibility a class violates the SRP. In section 10.3, we’ll discuss cohesion with a concrete example.
It can be difficult to stick to, but if you practice DI, one of the many benefits of Constructor Injection is that it becomes more obvious when you violate the SRP. (section 10.2.1)
Some years back, with one of my clients, I came across a class that contained over 90 dependencies. Those were all injected as abstractions into the constructor, so Dependency Injection was practiced. With over 90 dependencies, however, its hard to argue that such class does not violate the SRP—and that class absolutely did.
Even though the developers used DI, they were able to create a monster class that violated the SRP big time. That basically proves your point: DI does not enforce, nor automatically lead to SRP. But, on the other hand, as the book states, a class with many constructor arguments is a good indication that the SRP is violated. DI does make SRP violations more obvious, because the dependencies are clearly declared in a class's constructor. In the book we use a heuristic of 4 or 5 dependencies. Has a class crosses that number, it's time to take a good look at that class and check whether it violates the SRP principle (or any other SOLID principle for that matter).
Upvotes: 2