JPR
JPR

Reputation: 869

Too much dependency injection?

I'm currently re-factoring a large application with quite a bit of spaghetti legacy code into something more structured and easy to maintain, and most importantly, testable. I can see that obviously injecting classes dependencies into them as opposed to mixing object creation with business logic makes writing unit tests much easier.

I've read comments to the effect of "using dependency injection improperly causes more problems than it solves." What exactly does that mean? For such sophisticated verbiage, dependency injection seems like a pretty simple concept. How do you abuse the idea of sending dependencies in through a constructor rather than instantiating them within the dependent class? Why would the latter ever be preferable?

All I can see right now is that it makes isolating functionality to write tests and mocking objects extremely easy. It also seems to be making it ridiculously obvious when a class has too many responsibilities and points directly at classes that need to be refactored. Am I getting carried away if I'm avoiding the use of the new keyword anywhere other than my DI container (with the exception of core PHP classes)?

Upvotes: 4

Views: 896

Answers (1)

Ergwun
Ergwun

Reputation: 12978

I wouldn't worry about going overboard with dependency injection. You have already stated yourself some of the benefits that you have seen from adopting it (test-ability, encouraging good design re separation of concerns).

A criticism I have heard made of dependency injection (and IoC) is that it can introduce too much complexity. While it is certainly possible to over-complicate things due to a bad implementation, I can not agree with this complaint as an intrinsic problem with dependency injection.

The thing to keep an eye on is that you choose the right level of abstraction and indirection for your dependencies that will give you the flexibility you need. Too many levels of indirection can add complexity for no value, but I would argue that this is an orthogonal issue to dependency injection.

See this related question for more possible downsides to dependency injection :)


Regarding the issue of too many dependencies that you included in your original question prior to editing:

Having many dependencies can be a code smell, and the things to focus on to address this should be:

It sounds like you have already tackled part of your problem by following these principles. You should already look at whether your classes implement appropriate levels of abstraction. For example, your class that needs to access multiple data models may benefit from accessing them through a facade or repository.

Upvotes: 3

Related Questions