Dependency Injection Flashcards
What are the main advantages of DI?
- Reusability of code & decoupling of dependencies. Makes it easier to swap out implementations of a dependency. Inversion of control is introduced because classes don’t control how their dependencies are created, they will work with any config.
- Ease of refactoring. ?
- Ease of testing. When unit testing, you can pass in different implementations / sub classes of a class to test all of the different cases.
Why is tightly coupled code bad?
- No subclasses or alternative implementations can easily be used/passed to a class that constructs it’s own dependencies.
- ## Testing becomes more difficult because it prevents you from using a mock/dummy object.
What is an example of tightly coupled code?
An example of tightly coupled code is when an instance of a class is instantiated WITHIN another class rather than being dependency injected via the constructor.
What are the two main ways of doing manual dependency injection?
- Constructor injection
2. Field injection (setter methods)
What are the issues with manual dependency injection?
- Big apps have more and more layers of classes that inherit from each other. To instantiate the top class, you must manually provide all the dependencies for the classes below. This is tedious and can lead to boilerplate code.
What are the two categories of libraries that automate the process of creating & providing dependencies?
- Reflection-based libraries that connect dependencies at RUNTIME.
- Static solutions that generate the code to connect dependencies at COMPILE TIME.
What is dagger?
A dependency injection library for Kotlin/Java/Android that creates and manages the graph of dependencies for you. Provides static, compile-time dependencies that are better than using the reflection-based solutions.
What is the Service Locator pattern?
The service locator is a class that creates, stores and injects dependencies on demand.
What is the Service Locator like in comparison to Dependency Injection?
- In SL, classes are in control and ask for objects to be injected. In DI, the app is in control and has the required objects proactively injected by the system, without having to call a get/resolve method.
- It’s difficult to manage the lifetimes of objects because the dependencies have the scope of the entire app. DI objects exist only where they are injected, SL objects exist everywhere.
What is Hilt?
A Jetpack library for DI in Android. It provides containers for each Android class and manages their lifecycles automatically. It’s built ontop of Dagger to benefit from Daggers epicness.