依存性注入(DI) は、オブジェクトが依存するものを自分で作成するのではなく外部から受け取るパターンです。これはテスト可能性、保守性、柔軟性を向上させます。Androidでは、Hilt(Daggerに基づく)が推奨されるDIフレームワークです。
DIとは何か、そしてなぜ重要なのか
WITHOUT DI: a class CREATES its own dependencies (tightly coupled, hard to test/change):
class UserRepo { val api = ApiService() } // creates its own dependency — rigid
WITH DI: dependencies are PROVIDED from outside (injected):
class UserRepo(val api: ApiService) // receives it → flexible, testable
→ Benefits: TESTABILITY (inject mocks/fakes in tests), DECOUPLING, easier to swap
implementations, centralized dependency management, less boilerplate (with a framework).
