Your SlideShare is downloading. ×
Jesse Wilson from Square            Dagger                           A fast dependency injector                           ...
Watch the video with slide                         synchronization on InfoQ.com!                      http://www.infoq.com...
Presented at QCon San Francisco                          www.qconsf.comPurpose of QCon- to empower software development by...
Introduction                            Motivation                           Using Dagger                           Inside...
•Guice               Jesse       •javax.inject                           •Android Core LibrariesThursday, November 8, 12
Thursday, November 8, 12
We’re Hiring!      squareup.com/careersThursday, November 8, 12
Introduction                            Motivation                           Using Dagger                           Inside...
Motivation for                           Dependency                             Injection                    •Decouple con...
Dependency                             Injection                             Choices                    •PicoContainer    ...
(cc) creative commons from flickr.com/photos/getbutterfly/6317955134/Thursday, November 8, 12
(cc) creative commons from flickr.com/photos/wikidave/2988710537/Thursday, November 8, 12
We still love you,                                 Froyo                    •Eager vs. lazy graph construction            ...
“I didn’t really expect anyone to use                [git] because it’s so hard to use, but                that turns out ...
No black t-shirt                             necessaryThursday, November 8, 12
(cc) creative commons from flickr.com/photos/mike_miley/5969110684/Thursday, November 8, 12
CoffeeApp       •Know everything at                 CoffeeMaker               build time.       •Easy to see how          ...
Motivation for                                  Dagger                    •Its like Guice, but with speed                 ...
Introduction                            Motivation                           Using Dagger                           Inside...
Dagger?Thursday, November 8, 12
DAGger.Thursday, November 8, 12
DAGger.                           Directed                           Acyclic                           GraphThursday, Nove...
(cc) creative commons from flickr.com/photos/uscpsc/7894303566/Thursday, November 8, 12
(cc) creative commons from flickr.com/photos/uscpsc/7894303566/Thursday, November 8, 12
coffee maker                                                                             heater                            ...
CoffeeApp                                                                                 CoffeeMaker                     ...
! class Thermosiphon implements Pump {      !   private final Heater heater;      !           Thermosiphon(Heater heater) ...
Declare                               Dependencies                           class Thermosiphon implements Pump {         ...
Declare                               Dependencies                           class CoffeeMaker {                          ...
Satisfy                           Dependencies         @Module         class DripCoffeeModule {               @Provides He...
Build the Graph    class CoffeeApp {          public static void main(String[] args) {            ObjectGraph objectGraph ...
Neat features                    •Lazy<T>                    •Module overrides                    •MultibindingsThursday, ...
Lazy<T>                    class GridingCoffeeMaker {                      @Inject Lazy<Grinder> lazyGrinder;             ...
Module Overrides                @Module(                    includes = DripCoffeeModule.class,                    entryPoi...
Multibindings             @Module             class TwitterModule {               @Provides(type=SET) SocialApi provideApi...
Introduction                            Motivation                           Using Dagger                           Inside...
Graphs!Thursday, November 8, 12
Creating Graphs                    •Compile time                     •annotation processor                    •Runtime    ...
Using Graphs                    •Injection                    •Validation                    •Graphviz!Thursday, November ...
But how?                    •Bindings have names like                           “com.squareup.geo.LocationMonitor”        ...
final class CoffeeMaker$InjectAdapter extends Binding<CoffeeMaker> {              private Binding<Heater> f0;             ...
Validation                    •Eager at build time                    •Lazy at runtimeThursday, November 8, 12
dagger-compiler                    (cc) creative commons from flickr.com/photos/discover-central-california/8010906617Thurs...
javax.annotation.processing                       Built into javac                       Foolishly easy to use. Just put  ...
It’s a hassle                               (for us)                    •Coping with prebuilt .jar files                   ...
... and it’s limited                                (for you)                    •No private or final field access          ...
... but it’s smoking fast!            (for your users)                    •Startup time for Square Wallet                 ...
Different Platforms                          are Different                    •HotSpot                    •Android          ...
HotSpot:                    Java on the Server                    •The JVM is fast                    •Code bases are huge...
Android                    •Battery powered                    •Garbage collection causes jank                    •Slow re...
GWT                    •Code size really matters                    •Compiler does full-app                           opti...
API Design                       in the GitHub age                    •Forking makes it easy to stay small                ...
javax.inject                            public @interface Inject {}                           ! public @interface Named { ...
!   public interface Lazy<T> {                           !     T get();                           !   }                   ...
Introduction                            Motivation                           Using Dagger                           Inside...
Guice                    •Still the best choice for many apps                    •May soon be able to mix & match         ...
Dagger                    •Dagger 0.9 today!                    •Dagger 1.0 in 2012ish                    •Friendly open s...
square.github.com/daggerThursday, November 8, 12
Questions?  squareup.com/careers                         swank.ca  corner.squareup.com              jwilson@squareup.comTh...
Upcoming SlideShare
Loading in...5
×

Dagger: A Fast Dependency Injector for Android and Java

8,135

Published on

Video and slides synchronized, mp3 and slide download available at http://bit.ly/YA0YEx.

Jesse Wilson introduces Dagger, a dependency injection framework for Java, covering the motivation behind its creation, examples on how to use it and some of the internal details. Filmed at qconsf.com.

Jesse Wilson develops apps and open source at Square. He's worked on Android, Gson, Guice, Guava, and Shush.

Published in: Technology, News & Politics
2 Comments
24 Likes
Statistics
Notes
  • Sipho we're glad you liked it. Please check our presentation page to find more interesting presentations http://www.infoq.com/presentations/
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • This was a lovely presentation
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
8,135
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
2
Likes
24
Embeds 0
No embeds

No notes for slide

Transcript of "Dagger: A Fast Dependency Injector for Android and Java"

  1. 1. Jesse Wilson from Square Dagger A fast dependency injector for Android and Java.Thursday, November 8, 12
  2. 2. Watch the video with slide synchronization on InfoQ.com! http://www.infoq.com/presentations /Dagger InfoQ.com: News & Community Site• 750,000 unique visitors/month• Published in 4 languages (English, Chinese, Japanese and Brazilian Portuguese)• Post content from our QCon conferences• News 15-20 / week• Articles 3-4 / week• Presentations (videos) 12-15 / week• Interviews 2-3 / week• Books 1 / month
  3. 3. Presented at QCon San Francisco www.qconsf.comPurpose of QCon- to empower software development by facilitating the spread ofknowledge and innovationStrategy - practitioner-driven conference designed for YOU: influencers ofchange and innovation in your teams- speakers and topics driving the evolution and innovation- connecting and catalyzing the influencers and innovatorsHighlights- attended by more than 12,000 delegates since 2007- held in 9 cities worldwide
  4. 4. Introduction Motivation Using Dagger Inside Dagger Wrapping UpThursday, November 8, 12
  5. 5. •Guice Jesse •javax.inject •Android Core LibrariesThursday, November 8, 12
  6. 6. Thursday, November 8, 12
  7. 7. We’re Hiring! squareup.com/careersThursday, November 8, 12
  8. 8. Introduction Motivation Using Dagger Inside Dagger Wrapping UpThursday, November 8, 12
  9. 9. Motivation for Dependency Injection •Decouple concrete from concrete •UniformityThursday, November 8, 12
  10. 10. Dependency Injection Choices •PicoContainer •Spring •Guice •javax.injectThursday, November 8, 12
  11. 11. (cc) creative commons from flickr.com/photos/getbutterfly/6317955134/Thursday, November 8, 12
  12. 12. (cc) creative commons from flickr.com/photos/wikidave/2988710537/Thursday, November 8, 12
  13. 13. We still love you, Froyo •Eager vs. lazy graph construction •Reflection vs. codegenThursday, November 8, 12
  14. 14. “I didn’t really expect anyone to use [git] because it’s so hard to use, but that turns out to be its big appeal. No technology can ever be too arcane or complicated for the black t-shirt crowd.” –Linus Torvalds typicalprogrammer.com/?p=143Thursday, November 8, 12
  15. 15. No black t-shirt necessaryThursday, November 8, 12
  16. 16. (cc) creative commons from flickr.com/photos/mike_miley/5969110684/Thursday, November 8, 12
  17. 17. CoffeeApp •Know everything at CoffeeMaker build time. •Easy to see how Pump dependencies are Thermosiphon used & satisfied HeaterThursday, November 8, 12
  18. 18. Motivation for Dagger •Its like Guice, but with speed instead of features also... •Simple •PredictableThursday, November 8, 12
  19. 19. Introduction Motivation Using Dagger Inside Dagger Wrapping UpThursday, November 8, 12
  20. 20. Dagger?Thursday, November 8, 12
  21. 21. DAGger.Thursday, November 8, 12
  22. 22. DAGger. Directed Acyclic GraphThursday, November 8, 12
  23. 23. (cc) creative commons from flickr.com/photos/uscpsc/7894303566/Thursday, November 8, 12
  24. 24. (cc) creative commons from flickr.com/photos/uscpsc/7894303566/Thursday, November 8, 12
  25. 25. coffee maker heater thermosiphon pump (cc) creative commons from flickr.com/photos/uscpsc/7894303566/Thursday, November 8, 12
  26. 26. CoffeeApp CoffeeMaker Pump Thermosiphon Heater (cc) creative commons from flickr.com/photos/uscpsc/7894303566/Thursday, November 8, 12
  27. 27. ! class Thermosiphon implements Pump { ! private final Heater heater; ! Thermosiphon(Heater heater) { ! this.heater = heater; ! } ! @Override public void pump() { ! if (heater.isHot()) { ! System.out.println("=> => pumping => =>"); ! } ! } ! }Thursday, November 8, 12
  28. 28. Declare Dependencies class Thermosiphon implements Pump { private final Heater heater; @Inject Thermosiphon(Heater heater) { this.heater = heater; } ... }Thursday, November 8, 12
  29. 29. Declare Dependencies class CoffeeMaker { @Inject Heater heater; @Inject Pump pump; ... }Thursday, November 8, 12
  30. 30. Satisfy Dependencies @Module class DripCoffeeModule { @Provides Heater provideHeater() { return new ElectricHeater(); } @Provides Pump providePump(Thermosiphon pump) { return pump; } }Thursday, November 8, 12
  31. 31. Build the Graph class CoffeeApp { public static void main(String[] args) { ObjectGraph objectGraph = ObjectGraph.create(new DripCoffeeModule()); CoffeeMaker coffeeMaker = objectGraph.get(CoffeeMaker.class); coffeeMaker.brew(); } }Thursday, November 8, 12
  32. 32. Neat features •Lazy<T> •Module overrides •MultibindingsThursday, November 8, 12
  33. 33. Lazy<T> class GridingCoffeeMaker { @Inject Lazy<Grinder> lazyGrinder; public void brew() { while (needsGrinding()) { // Grinder created once and cached. Grinder grinder = lazyGrinder.get() grinder.grind(); } } }Thursday, November 8, 12
  34. 34. Module Overrides @Module( includes = DripCoffeeModule.class, entryPoints = CoffeeMakerTest.class, overrides = true ) static class TestModule { @Provides @Singleton Heater provideHeater() { return Mockito.mock(Heater.class); } }Thursday, November 8, 12
  35. 35. Multibindings @Module class TwitterModule { @Provides(type=SET) SocialApi provideApi() { ... } } @Module class GooglePlusModule { @Provides(type=SET) SocialApi provideApi() { ... } } ... @Inject Set<SocialApi>Thursday, November 8, 12
  36. 36. Introduction Motivation Using Dagger Inside Dagger Wrapping UpThursday, November 8, 12
  37. 37. Graphs!Thursday, November 8, 12
  38. 38. Creating Graphs •Compile time •annotation processor •Runtime •generated code loader •reflectionThursday, November 8, 12
  39. 39. Using Graphs •Injection •Validation •Graphviz!Thursday, November 8, 12
  40. 40. But how? •Bindings have names like “com.squareup.geo.LocationMonitor” •Bindings know the names of their dependencies, like “com.squareup.otto.Bus”Thursday, November 8, 12
  41. 41. final class CoffeeMaker$InjectAdapter extends Binding<CoffeeMaker> { private Binding<Heater> f0; private Binding<Pump> f1; public CoffeeMaker$InjectAdapter() { super("coffee.CoffeeMaker", ...); } public void attach(Linker linker) { f0 = linker.requestBinding("coffee.Heater", coffee.CoffeeMaker.class); f1 = linker.requestBinding("coffee.Pump", coffee.CoffeeMaker.class); } public CoffeeMaker get() { coffee.CoffeeMaker result = new coffee.CoffeeMaker(); injectMembers(result); return result; } public void injectMembers(CoffeeMaker object) { object.heater = f0.get(); object.pump = f1.get(); } public void getDependencies(Set<Binding<?>> bindings) { bindings.add(f0); bindings.add(f1); } }Thursday, November 8, 12
  42. 42. Validation •Eager at build time •Lazy at runtimeThursday, November 8, 12
  43. 43. dagger-compiler (cc) creative commons from flickr.com/photos/discover-central-california/8010906617Thursday, November 8, 12
  44. 44. javax.annotation.processing Built into javac Foolishly easy to use. Just put dagger-compiler on your classpath!Thursday, November 8, 12
  45. 45. It’s a hassle (for us) •Coping with prebuilt .jar files •Versioning •TestingThursday, November 8, 12
  46. 46. ... and it’s limited (for you) •No private or final field access •Incremental builds are imperfect •ProGuardThursday, November 8, 12
  47. 47. ... but it’s smoking fast! (for your users) •Startup time for Square Wallet on one device improved from ~5 seconds to ~2 secondsThursday, November 8, 12
  48. 48. Different Platforms are Different •HotSpot •Android •GWTThursday, November 8, 12
  49. 49. HotSpot: Java on the Server •The JVM is fast •Code bases are hugeThursday, November 8, 12
  50. 50. Android •Battery powered •Garbage collection causes jank •Slow reflection, especially on older devices •Managed lifecycleThursday, November 8, 12
  51. 51. GWT •Code size really matters •Compiler does full-app optimizations •No reflection. github.com/tbroyer/sheathThursday, November 8, 12
  52. 52. API Design in the GitHub age •Forking makes it easy to stay small & focusedThursday, November 8, 12
  53. 53. javax.inject public @interface Inject {} ! public @interface Named { ! String value() default ""; ! } ! public interface Provider { ! T get(); ! } ! public @interface Qualifier {} ! public @interface Scope {} ! public @interface Singleton {}Thursday, November 8, 12
  54. 54. ! public interface Lazy<T> { ! T get(); ! } ! public interface MembersInjector<T> { ! void injectMembers(T instance); ! } ! public final class ObjectGraph { ! public static ObjectGraph create(Object... modules); ! public ObjectGraph plus(Object... modules); ! public void validate(); ! public void injectStatics(); ! public <T> T get(Class type); dagger ! ! } public <T> T inject(T instance); ! public @interface Module { ! Class[] entryPoints() default { }; ! Class[] staticInjections() default { }; ! Class[] includes() default { }; ! Class addsTo() default Void.class; ! boolean overrides() default false; ! boolean complete() default true; ! } ! public @interface Provides { ! enum Type { UNIQUE, SET } ! Type type() default Type.UNIQUE; ! }Thursday, November 8, 12
  55. 55. Introduction Motivation Using Dagger Inside Dagger Wrapping UpThursday, November 8, 12
  56. 56. Guice •Still the best choice for many apps •May soon be able to mix & match with DaggerThursday, November 8, 12
  57. 57. Dagger •Dagger 0.9 today! •Dagger 1.0 in 2012ish •Friendly open source.Thursday, November 8, 12
  58. 58. square.github.com/daggerThursday, November 8, 12
  59. 59. Questions? squareup.com/careers swank.ca corner.squareup.com jwilson@squareup.comThursday, November 8, 12

×