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

Android Architecture (Dagger 2)

Android Architecture (Dagger 2)

Slides from my talk at Mobilatorium meetup

Alex Korovyansky

July 15, 2017
Tweet

More Decks by Alex Korovyansky

Other Decks in Programming

Transcript

  1. Dependency Injection • Software design pattern that implements inversion of

    control and allows a program design to follow the dependency inversion principle. The term was coined by Martin Fowler. • Separates behaviour of something from its required classes 2 Component Service
  2. public class Component { private final Service service; public Component()

    { this.service = new ServiceImpl(); } public void doStuff() { return service.doStuff(); } } 3 ? public interface Service { public void doStuff(); }
  3. 4 public class CatsService implements Service { @Override public void

    doStuff() { System.out.println("Cats are better than dogs!") } } public class DogsService implements Service { @Override public void doStuff() { System.out.println("Dogs are better than cats!") } }
  4. public class Component { private final Service service; public Component()

    { this.service = new CatsService(); } public void doStuff() { return service.doStuff(); } } 5 ? public interface Service { public void doStuff(); }
  5. 8 public class Component { private final Service service; public

    Component(Service service) { this.service = service; } public void doStuff() { return service.doStuff(); } } ^^ Constructor Injection ^^
  6. Advantages of DI • Loosely coupled programs • Following single

    responsibility principle • Easy to write tests / extend / maintain • Reduction of boilerplate code • Parallel development • … 11
  7. Guice • Powerful, dynamic, well-tested, wide-spread, etc… • Canonical standard

    for dependency injection • Configuration problems fail at runtime • Slow initialization, slow injection, memory problems 14
  8. Dagger2 • The first to implement the full stack with

    generated code • @Module + @Provides: mechanism for providing dependencies • @Inject: mechanism for requesting dependencies • @Component: bridge between @Module and @Inject 18
  9. Providing Dependencies • Modules are classes that provide dependencies •

    @Module annotation on the class • @Provider annotation on a method indicates that its return type is a dependency 19