I have a class that does too many things (many responsibilities). E.g. logging, loading data from various databases, methods that are doing extraneous calculation/processing as well as the main processing method that is this class's responsibility.
I have split the class to multiple classes each doing a specific thing and inject the classes to the original one.
The concern I have is that now I am injecting quite a few classes and I am not sure if that is considered bad design or code smell.
Is there some design pattern, similar as there is e.g. builder pattern for the case of having functions with too many parameters, that addresses the case of having many injected dependencies in a class?
CodePudding user response:
If your class has 8 dependencies, as you note in the comments, it likely means the class is exhibiting the Constructor Over-Injection code smell. This code smell is linked to the Single Responsibility Principle. It is an indication that your class is still doing too much.
There are many design patterns that can help you in further reducing the number of dependencies that the class had and therefore lowering the number of responsibilities and, in the end, lowering the complexity of these classes. Although there are many, two interesting patterns that come to my mind are:
- The Decorator design pattern; which is especially suited for extracting Cross-Cutting Concerns like logging out of the class that contains the core/business functionality
- The Facade Service refactoring; which hides a group of dependencies with their behavior behind a single, simplified abstraction, allowing the complexity of the original class to be reduced. This pattern is a specific form of the more general Extract Class refactoring.
I'm naming these two patterns because they are often beneficial in the context of DI. There are, of course, many more patterns and refactorings that might be applicable to your situation, but it not be useful trying to list them all. With concrete code examples, I might be able to give more specific guidance.
CodePudding user response:
If class has too many dependencies, then it is one if the sign that it does many things. So try to design your class to have fewer dependencies.
If you think that design of your class is okay, then you can try to group some classes into one and initialize it through dependency injection. This class will be like some one plase to do one tightly coupled operation.