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
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
public Component() { this.service = new ServiceImpl(); } public void doStuff() { return service.doStuff(); } } 3 ? ! ! ! public interface Service { public void doStuff(); }
@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!") } }
public Component() { this.service = new CatsService(); } public void doStuff() { return service.doStuff(); } } 5 ? ! ! ! public interface Service { public void doStuff(); }
• Fail as early as possible (compile-time, not runtime) • Eliminate reflection on methods and annotations at runtime • Have negligible memory impact 18
Wilson • Bob Lee served as technical advisor • “Giant” boolean switch in Square’s applications • 2 weeks after, they dropped Guice completely • Renamed to Dagger before first release 19
Wilson • Bob Lee served as technical advisor • “Giant” boolean switch in Square’s applications • 2 weeks after, they dropped Guice completely • Renamed to Dagger before first release • Open sourced — http://github.com/square/dagger 19
@Module annotation on the class • @Provider annotation on a method indicates that its return type is a dependency • Designed to be composed together 29
on a module • Used for aggressive static analysis • Potentially not needed for full compilation... • ...but absolutely required for incremental compilation 32
constructor arguments are dependencies • Dependencies can be stored in private and final fields • Dagger must create the object • @Provides not required for downstream injection 38
// Using constructor injection: TweeterApp app = og.get(TweeterApp.class); // Using field injection: TweeterApp app = new TweeterApp(); og.inject(app);
(impossible to use Constructor injection for OS components) • Field injection is Android style (including Activities, Fragments, Services, Views) • Application is the best place to keep ObjectGraph 46
(impossible to use Constructor injection for OS components) • Field injection is Android style (including Activities, Fragments, Services, Views) • Application is the best place to keep ObjectGraph • Modules and their “injects” segment parts of your app using .plus() method 46
on flavours and overriding of Modules) • Test mode for unit and functional testing (based on overriding Modules to follow test scenarios) • Mortar and Flow (work with UI with DI in mind) 52