SlideShare a Scribd company logo
1 of 59
Jesse Wilson from Square




            Dagger
                           A fast dependency injector
                              for Android and Java.
Thursday, November 8, 12
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
Presented at QCon San Francisco
                          www.qconsf.com
Purpose of QCon
- to empower software development by facilitating the spread of
knowledge and innovation
Strategy
 - practitioner-driven conference designed for YOU: influencers of
change and innovation in your teams
- speakers and topics driving the evolution and innovation
- connecting and catalyzing the influencers and innovators
Highlights
- attended by more than 12,000 delegates since 2007
- held in 9 cities worldwide
Introduction
                            Motivation
                           Using Dagger
                           Inside Dagger
                           Wrapping Up




Thursday, November 8, 12
•Guice
               Jesse       •javax.inject
                           •Android Core Libraries



Thursday, November 8, 12
Thursday, November 8, 12
We’re Hiring!
      squareup.com/careers



Thursday, November 8, 12
Introduction
                            Motivation
                           Using Dagger
                           Inside Dagger
                           Wrapping Up




Thursday, November 8, 12
Motivation for
                           Dependency
                             Injection

                    •Decouple concrete from concrete
                    •Uniformity

Thursday, November 8, 12
Dependency
                             Injection
                             Choices
                    •PicoContainer
                    •Spring
                    •Guice
                    •javax.inject
Thursday, November 8, 12
(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
                    •Reflection vs. codegen


Thursday, November 8, 12
“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=143
Thursday, November 8, 12
No black t-shirt
                             necessary


Thursday, 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                Pump




               dependencies are   Thermosiphon


               used & satisfied              Heater




Thursday, November 8, 12
Motivation for
                                  Dagger
                    •It's like Guice, but with speed
                           instead of features

                           also...



                    •Simple
                    •Predictable
Thursday, November 8, 12
Introduction
                            Motivation
                           Using Dagger
                           Inside Dagger
                           Wrapping Up




Thursday, November 8, 12
Dagger?




Thursday, November 8, 12
DAGger.




Thursday, November 8, 12
DAGger.

                           Directed
                           Acyclic
                           Graph

Thursday, November 8, 12
(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
                                                              thermosiphon pump




                           (cc) creative commons from flickr.com/photos/uscpsc/7894303566/
Thursday, November 8, 12
CoffeeApp




                                                                                 CoffeeMaker




                                                                            Pump




                                                                      Thermosiphon




                                                                                 Heater



                           (cc) creative commons from flickr.com/photos/uscpsc/7894303566/
Thursday, November 8, 12
! 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
Declare
                               Dependencies
                           class Thermosiphon implements Pump {
                             private final Heater heater;

                               @Inject
                               Thermosiphon(Heater heater) {
                                 this.heater = heater;
                               }

                               ...
                           }




Thursday, November 8, 12
Declare
                               Dependencies

                           class CoffeeMaker {
                             @Inject Heater heater;
                             @Inject Pump pump;

                               ...
                           }




Thursday, November 8, 12
Satisfy
                           Dependencies
         @Module
         class DripCoffeeModule {

               @Provides Heater provideHeater() {
                 return new ElectricHeater();
               }

               @Provides Pump providePump(Thermosiphon pump) {
                 return pump;
               }

         }


Thursday, November 8, 12
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
Neat features

                    •Lazy<T>
                    •Module overrides
                    •Multibindings


Thursday, November 8, 12
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
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
Multibindings
             @Module
             class TwitterModule {
               @Provides(type=SET) SocialApi provideApi() {
                 ...
               }
             }

             @Module
             class GooglePlusModule {
               @Provides(type=SET) SocialApi provideApi() {
                 ...
               }
             }

             ...

             @Inject Set<SocialApi>
Thursday, November 8, 12
Introduction
                            Motivation
                           Using Dagger
                           Inside Dagger
                           Wrapping Up




Thursday, November 8, 12
Graphs!



Thursday, November 8, 12
Creating Graphs
                    •Compile time
                     •annotation processor

                    •Runtime
                     •generated code loader
                     •reflection
Thursday, November 8, 12
Using Graphs

                    •Injection
                    •Validation
                    •Graphviz!


Thursday, November 8, 12
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
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
Validation


                    •Eager at build time
                    •Lazy at runtime


Thursday, November 8, 12
dagger-compiler



                    (cc) creative commons from flickr.com/photos/discover-central-california/8010906617
Thursday, November 8, 12
javax.annotation.processing

                       Built into javac
                       Foolishly easy to use. Just put
                       dagger-compiler on your classpath!



Thursday, November 8, 12
It’s a hassle
                               (for us)

                    •Coping with prebuilt .jar files
                    •Versioning
                    •Testing


Thursday, November 8, 12
... and it’s limited
                                (for you)

                    •No private or final field access
                    •Incremental builds are imperfect
                    •ProGuard


Thursday, November 8, 12
... but it’s smoking fast!
            (for your users)

                    •Startup time for Square Wallet
                           on one device improved from
                           ~5 seconds to ~2 seconds




Thursday, November 8, 12
Different Platforms
                          are Different

                    •HotSpot
                    •Android
                    •GWT


Thursday, November 8, 12
HotSpot:
                    Java on the Server

                    •The JVM is fast
                    •Code bases are huge


Thursday, November 8, 12
Android

                    •Battery powered
                    •Garbage collection causes jank
                    •Slow reflection, especially on older
                           devices
                    •Managed lifecycle

Thursday, November 8, 12
GWT
                    •Code size really matters
                    •Compiler does full-app
                           optimizations
                    •No reflection.

               github.com/tbroyer/sheath

Thursday, November 8, 12
API Design
                       in the GitHub age

                    •Forking makes it easy to stay small
                           & focused




Thursday, November 8, 12
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
!   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
Introduction
                            Motivation
                           Using Dagger
                           Inside Dagger
                           Wrapping Up




Thursday, November 8, 12
Guice

                    •Still the best choice for many apps
                    •May soon be able to mix & match
                           with Dagger




Thursday, November 8, 12
Dagger

                    •Dagger 0.9 today!
                    •Dagger 1.0 in 2012ish
                    •Friendly open source.



Thursday, November 8, 12
square.github.com/dagger




Thursday, November 8, 12
Questions?


  squareup.com/careers                         swank.ca
  corner.squareup.com              jwilson@squareup.com


Thursday, November 8, 12

More Related Content

Viewers also liked

MVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mixMVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mixFlorina Muntenescu
 
Js高级技巧
Js高级技巧Js高级技巧
Js高级技巧fool2fish
 
ഒരു അണ്‍സര്‍വ്വേ പ്രദേശത്തെ ഭൂപടനിര്‍മ്മാണപരിശ്രമം - കൂരാച്ചുണ്ടു് ഗ്രാമപഞ്ചാ...
ഒരു അണ്‍സര്‍വ്വേ പ്രദേശത്തെ ഭൂപടനിര്‍മ്മാണപരിശ്രമം - കൂരാച്ചുണ്ടു് ഗ്രാമപഞ്ചാ...ഒരു അണ്‍സര്‍വ്വേ പ്രദേശത്തെ ഭൂപടനിര്‍മ്മാണപരിശ്രമം - കൂരാച്ചുണ്ടു് ഗ്രാമപഞ്ചാ...
ഒരു അണ്‍സര്‍വ്വേ പ്രദേശത്തെ ഭൂപടനിര്‍മ്മാണപരിശ്രമം - കൂരാച്ചുണ്ടു് ഗ്രാമപഞ്ചാ...Jaisen Nedumpala
 
Depurando Aplicações PHP com XDebug e FirePHP - SETI 2008
Depurando Aplicações PHP com XDebug e FirePHP - SETI 2008Depurando Aplicações PHP com XDebug e FirePHP - SETI 2008
Depurando Aplicações PHP com XDebug e FirePHP - SETI 2008Jefferson Girão
 
Oscars after - party
Oscars after - partyOscars after - party
Oscars after - partyMakala D.
 
Balonmán touro
Balonmán touroBalonmán touro
Balonmán tourodavidares1
 
Php basics
Php basicsPhp basics
Php basicshamfu
 
Letter s presentatie
Letter s presentatieLetter s presentatie
Letter s presentatiecmagarry
 
برندسازی بین المللی احمدرضا اشرف العقلایی Dba7-mahan- کارآفرینی
برندسازی بین المللی احمدرضا اشرف العقلایی  Dba7-mahan- کارآفرینیبرندسازی بین المللی احمدرضا اشرف العقلایی  Dba7-mahan- کارآفرینی
برندسازی بین المللی احمدرضا اشرف العقلایی Dba7-mahan- کارآفرینیAshrafologhalaei Ahmadreza
 
Understanding Product/Market Fit
Understanding Product/Market FitUnderstanding Product/Market Fit
Understanding Product/Market FitGabor Papp
 

Viewers also liked (16)

MVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mixMVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mix
 
Giới thiệu chung về Du học Úc
Giới thiệu chung về Du học ÚcGiới thiệu chung về Du học Úc
Giới thiệu chung về Du học Úc
 
Js高级技巧
Js高级技巧Js高级技巧
Js高级技巧
 
Opinn aðgangur að vísindaefni
Opinn aðgangur að vísindaefniOpinn aðgangur að vísindaefni
Opinn aðgangur að vísindaefni
 
ഒരു അണ്‍സര്‍വ്വേ പ്രദേശത്തെ ഭൂപടനിര്‍മ്മാണപരിശ്രമം - കൂരാച്ചുണ്ടു് ഗ്രാമപഞ്ചാ...
ഒരു അണ്‍സര്‍വ്വേ പ്രദേശത്തെ ഭൂപടനിര്‍മ്മാണപരിശ്രമം - കൂരാച്ചുണ്ടു് ഗ്രാമപഞ്ചാ...ഒരു അണ്‍സര്‍വ്വേ പ്രദേശത്തെ ഭൂപടനിര്‍മ്മാണപരിശ്രമം - കൂരാച്ചുണ്ടു് ഗ്രാമപഞ്ചാ...
ഒരു അണ്‍സര്‍വ്വേ പ്രദേശത്തെ ഭൂപടനിര്‍മ്മാണപരിശ്രമം - കൂരാച്ചുണ്ടു് ഗ്രാമപഞ്ചാ...
 
Depurando Aplicações PHP com XDebug e FirePHP - SETI 2008
Depurando Aplicações PHP com XDebug e FirePHP - SETI 2008Depurando Aplicações PHP com XDebug e FirePHP - SETI 2008
Depurando Aplicações PHP com XDebug e FirePHP - SETI 2008
 
WONDERFUL
WONDERFULWONDERFUL
WONDERFUL
 
Ic tmagic tm clevedon
Ic tmagic tm clevedonIc tmagic tm clevedon
Ic tmagic tm clevedon
 
Oscars after - party
Oscars after - partyOscars after - party
Oscars after - party
 
Balonmán touro
Balonmán touroBalonmán touro
Balonmán touro
 
CEIP DE LAREDO //PROXECTO VALORA\\
CEIP DE LAREDO //PROXECTO VALORA\\CEIP DE LAREDO //PROXECTO VALORA\\
CEIP DE LAREDO //PROXECTO VALORA\\
 
Php basics
Php basicsPhp basics
Php basics
 
Letter s presentatie
Letter s presentatieLetter s presentatie
Letter s presentatie
 
برندسازی بین المللی احمدرضا اشرف العقلایی Dba7-mahan- کارآفرینی
برندسازی بین المللی احمدرضا اشرف العقلایی  Dba7-mahan- کارآفرینیبرندسازی بین المللی احمدرضا اشرف العقلایی  Dba7-mahan- کارآفرینی
برندسازی بین المللی احمدرضا اشرف العقلایی Dba7-mahan- کارآفرینی
 
20120319 aws meister-reloaded-s3
20120319 aws meister-reloaded-s320120319 aws meister-reloaded-s3
20120319 aws meister-reloaded-s3
 
Understanding Product/Market Fit
Understanding Product/Market FitUnderstanding Product/Market Fit
Understanding Product/Market Fit
 

More from C4Media

Streaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoStreaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoC4Media
 
Next Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileNext Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileC4Media
 
Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020C4Media
 
Understand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsUnderstand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsC4Media
 
Kafka Needs No Keeper
Kafka Needs No KeeperKafka Needs No Keeper
Kafka Needs No KeeperC4Media
 
High Performing Teams Act Like Owners
High Performing Teams Act Like OwnersHigh Performing Teams Act Like Owners
High Performing Teams Act Like OwnersC4Media
 
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaDoes Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaC4Media
 
Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideC4Media
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDC4Media
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine LearningC4Media
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at SpeedC4Media
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsC4Media
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsC4Media
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerC4Media
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleC4Media
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeC4Media
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereC4Media
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing ForC4Media
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data EngineeringC4Media
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreC4Media
 

More from C4Media (20)

Streaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoStreaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live Video
 
Next Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileNext Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy Mobile
 
Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020
 
Understand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsUnderstand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java Applications
 
Kafka Needs No Keeper
Kafka Needs No KeeperKafka Needs No Keeper
Kafka Needs No Keeper
 
High Performing Teams Act Like Owners
High Performing Teams Act Like OwnersHigh Performing Teams Act Like Owners
High Performing Teams Act Like Owners
 
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaDoes Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
 
Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate Guide
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CD
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine Learning
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at Speed
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep Systems
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.js
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly Compiler
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix Scale
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's Edge
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home Everywhere
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing For
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data Engineering
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
 

Recently uploaded

Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Skynet Technologies
 
Your enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jYour enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jNeo4j
 
Oauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoftOauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoftshyamraj55
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceSamy Fodil
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfFIDO Alliance
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxFIDO Alliance
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxFIDO Alliance
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe中 央社
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch TuesdayIvanti
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...panagenda
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxFIDO Alliance
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024Stephen Perrenod
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfFIDO Alliance
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentationyogeshlabana357357
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfSrushith Repakula
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGDSC PJATK
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FIDO Alliance
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...FIDO Alliance
 

Recently uploaded (20)

Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
Your enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jYour enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4j
 
Oauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoftOauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoft
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 

Dagger: A Fast Dependency Injector for Android and Java

  • 1. Jesse Wilson from Square Dagger A fast dependency injector for Android and Java. Thursday, November 8, 12
  • 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. Presented at QCon San Francisco www.qconsf.com Purpose of QCon - to empower software development by facilitating the spread of knowledge and innovation Strategy - practitioner-driven conference designed for YOU: influencers of change and innovation in your teams - speakers and topics driving the evolution and innovation - connecting and catalyzing the influencers and innovators Highlights - attended by more than 12,000 delegates since 2007 - held in 9 cities worldwide
  • 4. Introduction Motivation Using Dagger Inside Dagger Wrapping Up Thursday, November 8, 12
  • 5. •Guice Jesse •javax.inject •Android Core Libraries Thursday, November 8, 12
  • 7. We’re Hiring! squareup.com/careers Thursday, November 8, 12
  • 8. Introduction Motivation Using Dagger Inside Dagger Wrapping Up Thursday, November 8, 12
  • 9. Motivation for Dependency Injection •Decouple concrete from concrete •Uniformity Thursday, November 8, 12
  • 10. Dependency Injection Choices •PicoContainer •Spring •Guice •javax.inject Thursday, November 8, 12
  • 11. (cc) creative commons from flickr.com/photos/getbutterfly/6317955134/ Thursday, November 8, 12
  • 12. (cc) creative commons from flickr.com/photos/wikidave/2988710537/ Thursday, November 8, 12
  • 13. We still love you, Froyo •Eager vs. lazy graph construction •Reflection vs. codegen Thursday, November 8, 12
  • 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=143 Thursday, November 8, 12
  • 15. No black t-shirt necessary Thursday, November 8, 12
  • 16. (cc) creative commons from flickr.com/photos/mike_miley/5969110684/ Thursday, November 8, 12
  • 17. CoffeeApp •Know everything at CoffeeMaker build time. •Easy to see how Pump dependencies are Thermosiphon used & satisfied Heater Thursday, November 8, 12
  • 18. Motivation for Dagger •It's like Guice, but with speed instead of features also... •Simple •Predictable Thursday, November 8, 12
  • 19. Introduction Motivation Using Dagger Inside Dagger Wrapping Up Thursday, November 8, 12
  • 22. DAGger. Directed Acyclic Graph Thursday, November 8, 12
  • 23. (cc) creative commons from flickr.com/photos/uscpsc/7894303566/ Thursday, November 8, 12
  • 24. (cc) creative commons from flickr.com/photos/uscpsc/7894303566/ Thursday, November 8, 12
  • 25. coffee maker heater thermosiphon pump (cc) creative commons from flickr.com/photos/uscpsc/7894303566/ Thursday, November 8, 12
  • 26. CoffeeApp CoffeeMaker Pump Thermosiphon Heater (cc) creative commons from flickr.com/photos/uscpsc/7894303566/ Thursday, November 8, 12
  • 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. Declare Dependencies class Thermosiphon implements Pump { private final Heater heater; @Inject Thermosiphon(Heater heater) { this.heater = heater; } ... } Thursday, November 8, 12
  • 29. Declare Dependencies class CoffeeMaker { @Inject Heater heater; @Inject Pump pump; ... } Thursday, November 8, 12
  • 30. Satisfy Dependencies @Module class DripCoffeeModule { @Provides Heater provideHeater() { return new ElectricHeater(); } @Provides Pump providePump(Thermosiphon pump) { return pump; } } Thursday, November 8, 12
  • 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. Neat features •Lazy<T> •Module overrides •Multibindings Thursday, November 8, 12
  • 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. 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. 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. Introduction Motivation Using Dagger Inside Dagger Wrapping Up Thursday, November 8, 12
  • 38. Creating Graphs •Compile time •annotation processor •Runtime •generated code loader •reflection Thursday, November 8, 12
  • 39. Using Graphs •Injection •Validation •Graphviz! Thursday, November 8, 12
  • 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. 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. Validation •Eager at build time •Lazy at runtime Thursday, November 8, 12
  • 43. dagger-compiler (cc) creative commons from flickr.com/photos/discover-central-california/8010906617 Thursday, November 8, 12
  • 44. javax.annotation.processing Built into javac Foolishly easy to use. Just put dagger-compiler on your classpath! Thursday, November 8, 12
  • 45. It’s a hassle (for us) •Coping with prebuilt .jar files •Versioning •Testing Thursday, November 8, 12
  • 46. ... and it’s limited (for you) •No private or final field access •Incremental builds are imperfect •ProGuard Thursday, November 8, 12
  • 47. ... but it’s smoking fast! (for your users) •Startup time for Square Wallet on one device improved from ~5 seconds to ~2 seconds Thursday, November 8, 12
  • 48. Different Platforms are Different •HotSpot •Android •GWT Thursday, November 8, 12
  • 49. HotSpot: Java on the Server •The JVM is fast •Code bases are huge Thursday, November 8, 12
  • 50. Android •Battery powered •Garbage collection causes jank •Slow reflection, especially on older devices •Managed lifecycle Thursday, November 8, 12
  • 51. GWT •Code size really matters •Compiler does full-app optimizations •No reflection. github.com/tbroyer/sheath Thursday, November 8, 12
  • 52. API Design in the GitHub age •Forking makes it easy to stay small & focused Thursday, November 8, 12
  • 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. ! 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. Introduction Motivation Using Dagger Inside Dagger Wrapping Up Thursday, November 8, 12
  • 56. Guice •Still the best choice for many apps •May soon be able to mix & match with Dagger Thursday, November 8, 12
  • 57. Dagger •Dagger 0.9 today! •Dagger 1.0 in 2012ish •Friendly open source. Thursday, November 8, 12
  • 59. Questions? squareup.com/careers swank.ca corner.squareup.com jwilson@squareup.com Thursday, November 8, 12