C. Keith Ray

C. Keith Ray writes about and develops software in multiple platforms and languages, including iOS® and Macintosh®.
Keith's Résumé (pdf)

Saturday, December 9, 2017

WHY do Dependency Injection?

Many people have blogged on how to do dependency injection (DI), but few tell you why to use it.

What is dependency injection? It is the practice of passing objects that a class or method depends on, into the object or method, instead of the class or method creating that object itself.

Why use it? The purpose of dependency injection is to create a design for your code that is (a) testable, (b) separates responsibilities, and (c) is more flexible.

If your class or method creates objects and uses them, it could be argued that your code has too many responsibilities: creating objects is a difference responsibility than using them. That's a design argument for using DI.

If your class or method creates and uses objects it depends on, that makes unit testing it more difficult because your tests can't control or mock out those objects. This is the testing argument for using DI.

If your class or method creates and collaborates with objects it depends on, that makes re-using it to collaborate with different objects more difficult. This is the flexibility argument for using DI.

There's a nice description of using DI with Swift here:  https://cocoacasts.com/nuts-and-bolts-of-dependency-injection-in-swift/


No comments:

Post a Comment