I’m reading the Clean Code book and a chapter says that if a class has more than 3 dependencies is a code smell of that class isn’t doing one thing. Or what is the same, it isn’t following SRP. I’m thinking in certain scenarios in which I am unable to reset the number of dependencies to stick to that number.
Let’s say we have an app that connects to a public API REST what offers varied information about a lot entities in our domain. In our app we detect an use case repeated in many places where we request to the API the info about an entity with other dependent entities that it has.
The API REST doesn’t offer the data in the format we want because the calls when can make are to get data from a single table on the web database, not offers the data agrouped with other tables as we want. So our use case have to make different Api Call’s for to get all different data about the entities we need and then merge in the model we will use in the app.
To connect with the external subsystem we will hide implementation in a single Service class however this class has grown too much resulting a class with a lot methods to get data about all entities of the api rest. So we split this huge class into differents following the Repository pattern. Each class for each possible operations with an entity on the API.
Then, to hide all this concrete and common interaction with the service layer we will use a Facade class to coordinating all this calls. The problem I’m figuring it will have, is that it will have a lot dependencies in her constructor. Will have classes for each repository class and mapper classes to adapt the web data into app data.
The solution in these cases is merge all related dependencies in one so you reduce the number. One example is this: Refactoring to Aggregate Services. http://blog.ploeh.dk/2010/02/02/RefactoringtoAggregateServices/
But you merge when you see a clear relationship. What happend if in your class you can’t see that? All classes are granulated but all of them are necesary to achieve the goal but can’t not be merged in an aggregate service.
So my question is, the “rule” that more than three dependencies violates SRP is always applicable? Returning to our example, our facade needs to access many repository classes and mapper classes. The mapper classes can be hide on a agreggated service, maybe, but repository classes are fine like are. We could introduce a service locator to store them but it is a very bad practice.