4 Dependency Injection - G00fY2/android-mvp-wiki GitHub Wiki

4 Dependency Injection

Dependency Injection describes a software pattern which is linked to the last SOLID principle Dependency Inversion and the Inversion of Control design principle. The Dependency Inversion Principle is about isolating classes from concrete implementations and having them depend on abstract classes or interfaces. By programming against an interface you can prevent being tightly coupled to one implementation and losing flexibility. Closely linked to that is the Inversion of Control principle. It specifies that objects do not create other objects which they rely on. Dependency Injection is a from of IoC, where require objects (Dependencies) get passed (Injected) into the object through constructors or setters. So an object receives the objects it relies on without intervening itself. It makes the task of creating the object "someone else's problem".

4.1 Advantages

  • more reusable code: as dependency components can be configured externally (implementations of interfaces can be configured to work in different cases)
  • better testability: dependencies can be replaced by mocks to write unit tests
  • leads to the Single responsibility principle: class not responsible for dependencies
  • cleaner code: creating and forwarding dependencies inside objects can be quite complex