Constructor Injection: How many dependencies is too many?

Viewed 16938

I've been using manual constructor injection DI for a little bit now. One thing that I notice is that my constructors are starting to get rather long.

I have a class that depends on a bunch of little objects - anywhere between 6 and 10 sometimes. As I continue to break my application into smaller chunks, I could see this number increasing over time. Is this a common problem?

Obviously this is going to depend a great deal on the project. However, the basic question is this:

When do you start to get uncomfortable with the number of dependencies that a class has? What are some strategies that you use to reduce these dependencies?

6 Answers

This may be a sign that the class with the 6-10 dependencies itself needs to be refactored.

I would think no more than three or four. If you are getting more than that, I would start thinking about how well you are abstracting your concerns. A single repository object, for example, should fulfill all of your data retrieval needs within the class in question.

You may also want to see if any of the parameters to your constructor should be combined into a single class as well (assuming that the parameters make sense as a class).

It might also be that you want to look at using the ServiceLocator pattern for some of your dependencies. This is particularly true if you're having to pass the dependencies down a long chain of constructors.

Related