Junior
What is dependency injection (DI)?
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a design pattern where component dependencies are provided from outside rather than created by the component itself. This allows for greater flexibility, testability, and maintainability of the code.
Main principles:
- Inversion of Control (IoC): The component does not manage the creation of its dependencies.
- Separation of Concerns: Creating dependencies is separated from their usage.
Advantages of DI:
- Improved testability: Easily replace real dependencies with test mocks.
- Reduced coupling: Components become less dependent on each other.
- Increased flexibility and reusability: Easily change the implementation of dependencies without modifying the component code.
- Simplified dependency management: Especially in large projects.
Ways to implement DI in Android:
- Manual DI: Dependencies are passed via constructor or setters.
- Using frameworks: Dagger 2, Hilt, Koin. These frameworks automate the process of creating and providing dependencies.
Example manually:
// Dependency
interface AnalyticsManager {
fun trackEvent(eventName: String)
}
// Dependency implementation
class FirebaseAnalyticsManager : AnalyticsManager {
override fun trackEvent(eventName: String) {
// Firebase tracking logic
}
}
// Component that needs the dependency
class UserRepository(private val analyticsManager: AnalyticsManager) { // Dependency passed via constructor
fun getUser(userId: String): User? {
analyticsManager.trackEvent("UserFetched")
// Logic to get user
return null
}
}
// Place where objects are created and linked
fun main() {
val analytics: AnalyticsManager = FirebaseAnalyticsManager()
val userRepository = UserRepository(analytics) // Dependency injection
}