Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are dependency injection frameworks worth the extra indirection layer?

Do you find that dependency injection frameworks make code more difficult to follow? Does the indirection outweigh the benefit?

like image 203
BC. Avatar asked Feb 16 '09 22:02

BC.


People also ask

What are some disadvantages of dependency injection?

The main drawback of dependency injection is that using many instances together can become a very difficult if there are too many instances and many dependencies that need to be resolved.

Do I need a framework for dependency injection?

Dependency Injection is a pattern, not any particular framework. You could even implement it manually, but that would be too much trouble.

Should I use dependency injection everywhere?

So you should use dependency injection it would improve your code reuse and readability. You need to inject configuration data into one or more components. You need to inject the same dependency into multiple components. You need to inject different implementations of the same dependency.

Which choice is benefit of using dependency injection?

Advantages. A basic benefit of dependency injection is decreased coupling between classes and their dependencies. By removing a client's knowledge of how its dependencies are implemented, programs become more reusable, testable and maintainable.


2 Answers

Yes, your code becomes much more decoupled and much more testable. This in particular becomes handy when you have lots of tests and each test requires a heavy object such as database layers.

If you use dependency injection, you can simply create so called 'mock' objects or stubs and use those to let your tests run more quickly and have less side effects (database state).

It is true that you cannot see directly which implementation is used by looking at the code. You will see a reference to the interface. A good IDE might have functionallity to view all implementations for a particular interface, so use that to your advantage.

like image 144
TomHastjarjanto Avatar answered Oct 02 '22 15:10

TomHastjarjanto


For non-trivial "enterprisey" apps, yes it's worth it. Before DI frameworks, every shop implemented its own fancy "ServiceLocator" class in some internal library that their other projects used. So you had calls to that thing littered throughout the codebase.

Those calls represented the objects' need to discover/configure their own dependencies. The DI framework eliminates all that code, so your objects become simpler and therefore, easier to test.

Now, it follows that if you don't have a lot of variability in your objects' dependencies, the value of the indirection (the centralized configuration) is less for you.

For more details contrasting DI to ServiceLocator, see Fowler's Inversion of Control Containers and the Dependency Injection pattern

like image 38
jcrossley3 Avatar answered Oct 02 '22 15:10

jcrossley3