Upgrade to Pro — share decks privately, control downloads, hide ads and more …

To inject or not to inject: Dependency Injection with Kotlin (Droidcon Nairobi)

To inject or not to inject: Dependency Injection with Kotlin (Droidcon Nairobi)

Dependency Injection via frameworks like Dagger was present in most modern Android projects.
But then Kotlin happened. And since then a bunch of new libraries like Koin or Kodein appeared. Developers are even writing articles about how to do DI without any framework.
Some argue that those don’t even offer real dependency injection. Let’s look at that argument and compare the approaches.
So, is there something wrong with Dagger & co. in Kotlin? Are they obsolete? What are the alternatives? Let’s dive in.

Danny Preussler

October 05, 2018
Tweet

More Decks by Danny Preussler

Other Decks in Programming

Transcript

  1. .droidconKe To Inject or not to Inject Dependency Injection with

    Kotlin Danny Preussler sporttotal.tv @PreusslerBerlin
  2. about:me • Java developer since 2003 • Talks about testing

    and architecture on mobile since 2008 • Kotlin since 2016 • Google Developer Expert for Android and Kotlin • Worked for eBay, Groupon, Viacom
  3. sporttotal.tv • We are streaming under-medialised sports • Looking for

    Backend/Frontend Lead (Berlin) • Looking for iOS Developer (Berlin) • Looking for Designer (Köln, Berlin)
  4. @PreusslerBerlin class MainActivity : Activity() { private val tracker =

    GoogleAnalyticsTracker() override fun onCreate(state: Bundle?) { super.onCreate(state) setContentView(R.layout.activity_main) tracker.trackStarted() } }
  5. @PreusslerBerlin class MainActivity : Activity() { private val tracker =

    GoogleAnalyticsTracker() override fun onCreate(state: Bundle?) { super.onCreate(state) setContentView(R.layout.activity_main) tracker.trackStarted() } } Not testable!
  6. @PreusslerBerlin class MainActivity : Activity() { private val tracker =

    GoogleAnalyticsTracker() override fun onCreate(state: Bundle?) { super.onCreate(state) setContentView(R.layout.activity_main) tracker.trackStarted() } } Google Analytics is implementation detail Single Resposibility Not testable
  7. Inversion of Control Common implementations: • Factory • Service Locator

    tracker = Locator.get(Tracker::class) • Dependency Injection
  8. Inversion of Control Common implementations: • Factory • Service Locator

    • Dependency Injection @Inject val tracker: Tracker
  9. @PreusslerBerlin Dagger2 • Dagger1 by Square, Dagger2 by Google •

    Most popular dependency injection library in Android • Very fast at runtime • Complete runtime validation
  10. @PreusslerBerlin Problems of Dagger: • Complex • Hard learning curve

    • Lot of boilerplate • Not very good for testing @PreusslerBerlin
  11. @PreusslerBerlin How can Kotlin help? • Lazy • Delegates •

    Type inference • Inlining (generic T) • Lambdas • Functional programming @PreusslerBerlin
  12. @PreusslerBerlin Default arguments class PlayerViewModel( val schedulers: RxSchedulers = DefaultSchedulers())

    vs class PlayerViewModel( val schedulers: RxSchedulers) @Inject constructor(): this(DefaultSchedulers())
  13. @PreusslerBerlin Martin says: • both provide fundamental decoupling • In

    both: application code is independent of the concrete implementation
  14. @PreusslerBerlin Martin says: important difference is about how implementation is

    provided • With service locator: the class asks for it • With injection there is no explicit request • With a Service Locator every user has a dependency to the locator
  15. @PreusslerBerlin Martin says: So the decision between locator and injector

    depends on whether that dependency is a problem.
  16. @PreusslerBerlin inline fun <reified T : Any> get(…): T =

    … resolveByClass(T::class, …) Behind by inject:
  17. @PreusslerBerlin inline fun <reified T : Any> get(…): T =

    … resolveByClass(T::class, …) Behind by inject:
  18. @PreusslerBerlin inline fun <reified T : Any> get(…): T =

    … resolveByClass(T::class, …) Behind by inject:
  19. @PreusslerBerlin The android problem • Normally constructor injection preferred •

    On Android: framework classes need field/setter injection: Activity, Service, Fragment, Views Android central
  20. @PreusslerBerlin The annotated contructor issue • @Inject to mark constructor

    is handy: class HomeViewModel @Inject constructor(val resources: Resources) • Violates separations of concerns • Violates clean architecture : DI should stay in outermost layer • Providers are the cleaner solution anyway (part of JSR330)
  21. @PreusslerBerlin The annotated constructor issue • @Inject to mark constructor

    is handy: class HomeViewModel @Inject constructor(val resources: Resources) • Violates separations of concerns • Violates clean architecture : DI should stay in outermost layer • Providers are the cleaner solution anyway (part of JSR330)
  22. @PreusslerBerlin The annotated contructor issue • @Inject to mark constructor

    is handy: class HomeViewModel @Inject constructor(val resources: Resources) • Violates separations of concerns • Violates clean architecture : DI should stay in outermost layer • Providers are the cleaner solution anyway (part of JSR330)
  23. @PreusslerBerlin The annotated contructor issue • @Inject to mark constructor

    is handy: class HomeViewModel @Inject constructor(val resources: Resources) • Violates separations of concerns • Violates clean architecture : DI should stay in outermost layer • Providers are the cleaner solution anyway (part of JSR330)
  24. @PreusslerBerlin Boilerplate • Manual dependency injection has zero fixed cost

    …scales poorly. • A service locator has some overhead in creating it, inserting the bindings, and then doing the lookups. • A dependency injector has a lot of fixed overhead in setting up an injector hierarchy (components in Dagger 2) and all the modules to provide bindings. https://www.reddit.com/r/androiddev/comments/8ch4cg/dagger2_vs_koin_for_dependency_injection/
  25. @PreusslerBerlin Boilerplate • Manual dependency injection has zero fixed cost

    …scales poorly. • A service locator has some overhead in creating it, inserting the bindings, and then doing the lookups. • A dependency injector has a lot of fixed overhead in setting up an injector hierarchy (components in Dagger 2) and all the modules to provide bindings. https://www.reddit.com/r/androiddev/comments/8ch4cg/dagger2_vs_koin_for_dependency_injection/
  26. @PreusslerBerlin Boilerplate • Manual dependency injection has zero fixed cost

    …scales poorly. • A service locator has some overhead in creating it, inserting the bindings, and then doing the lookups. • A dependency injector has a lot of fixed overhead in setting up an injector hierarchy (components in Dagger 2) and all the modules to provide bindings. https://www.reddit.com/r/androiddev/comments/8ch4cg/dagger2_vs_koin_for_dependency_injection/
  27. @PreusslerBerlin Boilerplate • if you're going to write a serious

    app with hundreds of bindings and hundreds of injected types with a deep graph of types then you're better off with a proper injector that generates the code that you otherwise manually write worth Koin. https://www.reddit.com/r/androiddev/comments/8ch4cg/dagger2_vs_koin_for_dependency_injection/ only true when using @ constructor
  28. @PreusslerBerlin Where are we? • Choice depends on scale •

    Hard dependency to SL framework • Performance comparable • Compile-time validation
  29. @PreusslerBerlin Compile time validation? • Whose job is it to

    manage the nulls. The language? Or the programmer? • Defects are the fault of programmers. It is programmers who create defects – not languages. • And what is it that programmers are supposed to do to prevent defects? • TEST! https://blog.cleancoder.com/uncle-bob/2017/01/11/TheDarkPath.html
  30. @PreusslerBerlin Tests • Koin has dryRun()to verify the module setup

    • Have a test spawning up all fragments/activities to see if breaking change was added
  31. @PreusslerBerlin Access the real thing in test (Koin) dependencies {

    testImplementation 'org.koin:koin-test:1.0.0‘ } val preferences: Persistence by inject()
  32. @PreusslerBerlin Override for tests (Koin) val resources = mock<Resources>() @BeforeEach

    fun setup() { StandAloneContext.loadKoinModules( module { factory(override = true) { resources } }) }
  33. @PreusslerBerlin Tags/Names • Dagger/Toothpick: @Named(„api1“) • Koin: factory <Api>(" api1

    ") { …. } by inject (name = „api“) • Kodein bind<Api>(tag = “api1") with … by kodein.instance(tag = “api1")
  34. @PreusslerBerlin Scoping • Toothpick Ktx: scope(SCOPE, { module { //

    bindings • Koin: module { scope(SCOPE) { // bindings }} • Kodein Kodein { bind<API>() with scoped(SCOPE)…
  35. @PreusslerBerlin Other Features • Android module • Koin has direct

    support for architecture components • Multi modules support • Non JVM Kotlin projects Koin ✓ Kodein ✓
  36. @PreusslerBerlin Transition • Depends on how well you hide the

    DI in your project • Replace all @inject with manual binding calls will be painful flickr.com/photos/anca_bejinaru/5234037866/
  37. @PreusslerBerlin Transition • Depends on how well you hide the

    DI in your project • Replace all @inject with manual binding calls will be painful (could be a first step) flickr.com/photos/anca_bejinaru/5234037866/
  38. @PreusslerBerlin Transition • Depends on how well you hide the

    DI in your project • Replace all @inject with manual binding calls will be painful • Kodein helps with reflection based javax.inject implementation flickr.com/photos/anca_bejinaru/5234037866/
  39. @PreusslerBerlin Transition • Depends on how well you hide the

    DI in your project • Replace all @inject with manual binding calls will be painful • Kodein helps with reflection based javax.inject implementation (keeps your project running) flickr.com/photos/anca_bejinaru/5234037866/
  40. @PreusslerBerlin Transition • Might end up in awkward readable syntax

    factory { HomeViewModel(get(), get(), get(), get(), get(), get()) } flickr.com/photos/anca_bejinaru/5234037866/
  41. @PreusslerBerlin Transition • Might end up in awkward readable syntax

    • Actually a code smell • Reflective approach available now factory { build<HomeViewModel> } flickr.com/photos/anca_bejinaru/5234037866/
  42. @PreusslerBerlin Sum up • Koin: • Pro: lightweight, easy •

    Contra: Limited • Kodein • Pro: Feature rich • Contra: Too many features • DI is simple concept, keep it simple!
  43. @PreusslerBerlin Give it a try • Kodein https://github.com/Kodein-Framework/Kodein-DI • Koin

    https://github.com/Ekito/koin • Toothpick KTX https://github.com/sporttotal-tv/toothpick-kotlin-extensions