Alex Rivera | Logout

Dependency Injection - What to do when you have a lot of dependencies?

Asked 2012-03-13T14:59:24.650
17

I have a class A that depends on 10 other classes. According to Dependency Injection pattern, i should pass all dependencies of A by its constructor.

So lets assume this constructor (of course this is not a working or real code, since I am not allowed to post the real code here)

public ClassA(ClassB b, ClassC c, ClassD d, ClassE e, ClassF f, ClassG g, ClassH h, ClassI i) {
  this.b = b;
  this.c = c;
  this.d = d;
  this.e = e;
  this.f = f;
  this.g = g;
  this.h = h;
  this.i = i;
}

I have read on Martin Fowler's book about refactoring that having a method with a lot of parameters is a code smell and should not happen.

My question is: is this OK when we are talking about DI? Is there a better way of inject dependencies without breaking Martin Fowler's rules?

I know I could pass the dependencies through properties, but that may cause errors since no one is really sure what should be pass in order that the class works.

EDIT

Thanks for all your answers. I will try now to demonstrate some of class A dependencies:

1 - A class to access a DB
2 - Another class to access another DB (yes, i need to perform operations on two databases)
3 - A class to send error notifications by email
4 - A class to load configurations
5 - A class that will act as timer for some operations (maybe this one can be avoided)
6 - A class with business logic

There any many others that i am trying to get rid of, but those are really necessary and I dont see any ways of avoiding them.

EDIT

After some refactoring now i have 7 dependencies (down from 10). But I have 4 DAO objects:

CustomerDAO
ProcessDAO
ProductsDAO
CatalogDAO

Is it correct do create another class called MyProjectDAO and inject those DAOS onto it? This way I will have only one DAO class that aggregates all DAO objects of my projec

Edit
Report

1 Answer

20

In my experience:

  • Try to design your class so it needs fewer dependencies. If it needs that many, it may have too many responsibilities.
  • If you're really convinced that your class design is appropriate, consider whether it may make sense for some of those dependencies to be joined together (e.g. via an adapter which takes responsibility for one "big" operation your class needs by delegating to a few of the dependencies). You can then depend on the adapter instead of the "smaller" dependencies.
  • If every other bit really makes sense, just swallow the smell of having a lot of parameters. It happens sometimes.
answered 2012-03-13T15:01:59.827

Your Answer