Dependency Injection – Many Dependencies in a Delegating Class

dependency-injection

I'm going through the code of the biggest program I've ever created from scratch and seeing if there are things that I can improve in the design. When I first created the program, I was using Singleton everywhere, but since then I've removed them completely and instead switched over to using Dependency Injection. One thing I noticed is that some of the classes have kind of beefy constructors since I inject all the needed classes. For example, I have one class that reads messages from a serial port and then saves them to a message queue. Then I have a class called MessageHandler that collects messages from the queue and then delegates them to the correct part of the system. This MessageHandler class currently has six classes injected in the constructor. Is this ok for a class that basically just forwards the messages to the correct receiver or is it a sign that I need to rethink my design?

Best Answer

You want to keep the amount of dependencies low. A class with many dependencies probably violates separation of concerns.

But there is no hard and fast rule about how many dependencies are too many. Six dependencies does not immediately sound like a problem to me, it very much depends on the individual case.

It is not in itself a problem if a class does nothing else than delegate. This is for example what the adapter pattern does.

Related Topic