SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

Destacado

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
Công ty Du học Toàn cầu ASCI
 
Php basics
Php basicsPhp basics
Php basics
hamfu
 

Destacado (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
 

Más de C4Media

Más de 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
 

Último

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Último (20)

Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 

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