SlideShare una empresa de Scribd logo
1 de 22
Descargar para leer sin conexión
ABUSING
DEPENDENCY INJECTION
WITH DAGGER
FOR DUMMIES
Saúl Díaz (@sefford)
Freakend ‘15
new Flipper(new Gintonic(new Gin(new Alcohol())))
FlipperGintonic GinAlcohol
SHOULD I USE DI WITH MY
PERSONAL/PRO PROJECT?
BASIC DAGGER FOR
DUMMIES
Flipper
Gin
Alcohol
Gintonic
Tonic
Trolling
Code
Google
Engineer
Tears
Android
@Module(
includes = RosieModule.class,
addsTo = {AndroidModule.class,
DrinkModule.class,
CodingModule.class
}
injects = FlipperFragment.class,
complete = true,
)
public class FlipperModule {
@Provides
@Named(“Tuenti”)
public FlipperInterface provideFlipper(Gintonic drink,
Trolling trolling, Android android) {
return new FlipperImpl(drink, trolling,
android);
}
}
public class FlipperFragment extends Fragment {
ObjectGraph graph;
@Inject
FlipperInterface flipper;
@Override
public void onCreate(Bundle bundle) {
graph = ObjectGraph.create(new FlipperModule());
graph.inject(this);
FlipperInterface flipper2 = graph.get(Flipper.class);
}
IDSPISPOPD FOR SINGLETONS
@Singleton
● By definition, Singletons cannot be tested
● Provides same instance of class for Graph
● This instance is not static
ADVANCED DAGGER
FOR DUMMIES
Lazy<Flipper> lazyFlipper;
● Creates the instance on lazyFlipper.get()
● Returns always the same instance (d’oh)
● Always done in UIThread!
LAZY INITIALIZATIONS
PROVIDING INSTANCES
Provider<Flipper> flipperProvider;
● Can help building your own Flipper army
● Returns a different instance each time
@Module(
override = true;
injects = FlipperFragment.class,
complete = true,
)
public class FlipperTestModule {
@Provides
@Singleton
public FlipperInterface provideFlipper() {
return mock(FlipperInterface.class);
}
}
MOCKING INSTANCES
DYNAMIC (SCOPED) INJECTION
public ObjectGraph extend() {
return graph.plus(new ExtensionModule1(),
new ExtensionModule2());
}
STATIC INJECTION
● Reduce boilerplate and mantenibility by
annotating classes and constructions
● Compilation-validated graph
SCOPED INJECTION
● Using a SOLID approach, change
implementations on runtime
● Graph runtime, validated
● Risk of “BOOOOOOM”
ABUSING INJECTION
FOR DUMMIES
CLASSIC EXAMPLE
@Module(injects = LoginActivity.class,
addsTo = AppModule.class)
// @author Antonio Leiva
public class LoginModule {
private LoginView view;
public LoginModule(LoginView view) {
this.view = view;
}
@Provides @Singleton public LoginView provideView() {
return view;
}
@Provides @Singleton
public LoginPresenter providePresenter(LoginView loginView,
LoginInteractor loginInteractor) {
return new LoginPresenterImpl(loginView, loginInteractor);
}
}
WHY STOPPING THERE?public class NoNfcModule() {
@Provides
public NfcInterfaceController provideNfcController() {
return new NullNfcController();
}
}
public class NfcModule() {
@Provides
public NfcInterfaceController provideNfcController(
NfcAdapter adapter) {
return new NfcController(adapter);
}
}
// This goes on Api15Module
@Provides
@Singleton
public StatusBarControllerInterface provideStatusBarControllerInterface() {
return new StatusBarAPI15Controller();
}
// This goes on Api19Module
@Provides
@Singleton
public StatusBarControllerInterface provideStatusBarControllerInterface() {
return new StatusBarAPI19Controller();
}
// This goes on Api21Module
@Provides
@Singleton
public StatusBarControllerInterface provideStatusBarControllerInterface() {
return new StatusBarAPI21Controller();
}
ONE MORE CUP OF ABUSEpublic class ActiveProfileModule() {
@Provides
public ProfilePresenterInterface provideProfilePres(...) {
return new
ActiveProfilePresenter(basePresenter,...);
}
}
public class RegularProfileModule() {
@Provides
public ProfilePresenterInterface provideProfilePres(...) {
return new
RegularProfilePresenter(basePresenter,...);
}
}
QUESTIONS?
THANKS!

Más contenido relacionado

La actualidad más candente

Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFPierre-Yves Ricau
 
Dependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutesDependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutesAntonio Goncalves
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02rhemsolutions
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Ontico
 
Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2Kirill Rozov
 
What’s new in Android JetPack
What’s new in Android JetPackWhat’s new in Android JetPack
What’s new in Android JetPackHassan Abid
 
Guice tutorial
Guice tutorialGuice tutorial
Guice tutorialAnh Quân
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized projectFabio Collini
 
Under the Hood: Using Spring in Grails
Under the Hood: Using Spring in GrailsUnder the Hood: Using Spring in Grails
Under the Hood: Using Spring in GrailsBurt Beckwith
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Fabio Collini
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideVisual Engineering
 
MCE^3 - Gregory Kick - Dagger 2
MCE^3 - Gregory Kick - Dagger 2 MCE^3 - Gregory Kick - Dagger 2
MCE^3 - Gregory Kick - Dagger 2 PROIDEA
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design PatternsGodfrey Nolan
 
Dependency injection with dagger 2
Dependency injection with dagger 2Dependency injection with dagger 2
Dependency injection with dagger 2Nischal0101
 

La actualidad más candente (20)

Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SF
 
Dependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutesDependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutes
 
Vue next
Vue nextVue next
Vue next
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02
 
CDI: How do I ?
CDI: How do I ?CDI: How do I ?
CDI: How do I ?
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
 
Open sourcing the store
Open sourcing the storeOpen sourcing the store
Open sourcing the store
 
Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2
 
What’s new in Android JetPack
What’s new in Android JetPackWhat’s new in Android JetPack
What’s new in Android JetPack
 
Guice tutorial
Guice tutorialGuice tutorial
Guice tutorial
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized project
 
Under the Hood: Using Spring in Grails
Under the Hood: Using Spring in GrailsUnder the Hood: Using Spring in Grails
Under the Hood: Using Spring in Grails
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
継承だろJK
継承だろJK継承だろJK
継承だろJK
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
Di code steps
Di code stepsDi code steps
Di code steps
 
MCE^3 - Gregory Kick - Dagger 2
MCE^3 - Gregory Kick - Dagger 2 MCE^3 - Gregory Kick - Dagger 2
MCE^3 - Gregory Kick - Dagger 2
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design Patterns
 
Dependency injection with dagger 2
Dependency injection with dagger 2Dependency injection with dagger 2
Dependency injection with dagger 2
 

Destacado

Danielle\'s Visual Resume
Danielle\'s Visual ResumeDanielle\'s Visual Resume
Danielle\'s Visual Resumedmhami3
 
Hot skills исследование страховых компаний_2011
Hot skills исследование страховых компаний_2011Hot skills исследование страховых компаний_2011
Hot skills исследование страховых компаний_2011Sergey Onenko
 
งานนำเสนอ1
งานนำเสนอ1งานนำเสนอ1
งานนำเสนอ1cattyloverose
 
สนใจ ไม่ได้แปลว่าได้ใจ
สนใจ ไม่ได้แปลว่าได้ใจสนใจ ไม่ได้แปลว่าได้ใจ
สนใจ ไม่ได้แปลว่าได้ใจnudeJEH
 
McCormack -EDIM510- Online Presentation Assignment
McCormack -EDIM510- Online Presentation AssignmentMcCormack -EDIM510- Online Presentation Assignment
McCormack -EDIM510- Online Presentation AssignmentWilkes University
 
Danielle\'s Visual Resume
Danielle\'s Visual ResumeDanielle\'s Visual Resume
Danielle\'s Visual Resumedmhami3
 
2012.7.31 第二回 Stage3D 勉強会「モデリングを始めてみよう」
2012.7.31 第二回 Stage3D 勉強会「モデリングを始めてみよう」2012.7.31 第二回 Stage3D 勉強会「モデリングを始めてみよう」
2012.7.31 第二回 Stage3D 勉強会「モデリングを始めてみよう」itoz itoz
 
Open im vol16_lt_hosi_factory
Open im vol16_lt_hosi_factoryOpen im vol16_lt_hosi_factory
Open im vol16_lt_hosi_factoryNTTDATA INTRAMART
 
Presentatie Astorium
Presentatie AstoriumPresentatie Astorium
Presentatie AstoriumMustafa Cevik
 
Agile2015 short paper presentation: Development of Complex Software with Agil...
Agile2015 short paper presentation: Development of Complex Software with Agil...Agile2015 short paper presentation: Development of Complex Software with Agil...
Agile2015 short paper presentation: Development of Complex Software with Agil...Alan Braz
 
Online Training @ Nitade Chula
Online Training @ Nitade ChulaOnline Training @ Nitade Chula
Online Training @ Nitade ChulanudeJEH
 
Subsalt Steep Dip Imaging Study with 3D Acoustic Modeling
Subsalt Steep Dip Imaging Study  with 3D Acoustic  ModelingSubsalt Steep Dip Imaging Study  with 3D Acoustic  Modeling
Subsalt Steep Dip Imaging Study with 3D Acoustic Modelingleizhuo
 

Destacado (20)

Danielle\'s Visual Resume
Danielle\'s Visual ResumeDanielle\'s Visual Resume
Danielle\'s Visual Resume
 
Triconf
TriconfTriconf
Triconf
 
Hot skills исследование страховых компаний_2011
Hot skills исследование страховых компаний_2011Hot skills исследование страховых компаний_2011
Hot skills исследование страховых компаний_2011
 
งานนำเสนอ1
งานนำเสนอ1งานนำเสนอ1
งานนำเสนอ1
 
สนใจ ไม่ได้แปลว่าได้ใจ
สนใจ ไม่ได้แปลว่าได้ใจสนใจ ไม่ได้แปลว่าได้ใจ
สนใจ ไม่ได้แปลว่าได้ใจ
 
McCormack -EDIM510- Online Presentation Assignment
McCormack -EDIM510- Online Presentation AssignmentMcCormack -EDIM510- Online Presentation Assignment
McCormack -EDIM510- Online Presentation Assignment
 
Sampleslideshow
SampleslideshowSampleslideshow
Sampleslideshow
 
Danielle\'s Visual Resume
Danielle\'s Visual ResumeDanielle\'s Visual Resume
Danielle\'s Visual Resume
 
2012.7.31 第二回 Stage3D 勉強会「モデリングを始めてみよう」
2012.7.31 第二回 Stage3D 勉強会「モデリングを始めてみよう」2012.7.31 第二回 Stage3D 勉強会「モデリングを始めてみよう」
2012.7.31 第二回 Stage3D 勉強会「モデリングを始めてみよう」
 
In kor we Trust
In kor we TrustIn kor we Trust
In kor we Trust
 
Open im vol16_lt_hosi_factory
Open im vol16_lt_hosi_factoryOpen im vol16_lt_hosi_factory
Open im vol16_lt_hosi_factory
 
QOL
QOLQOL
QOL
 
Mirsis Corporate Overview
Mirsis Corporate OverviewMirsis Corporate Overview
Mirsis Corporate Overview
 
Presentatie Astorium
Presentatie AstoriumPresentatie Astorium
Presentatie Astorium
 
Teste
TesteTeste
Teste
 
Agile2015 short paper presentation: Development of Complex Software with Agil...
Agile2015 short paper presentation: Development of Complex Software with Agil...Agile2015 short paper presentation: Development of Complex Software with Agil...
Agile2015 short paper presentation: Development of Complex Software with Agil...
 
Online Training @ Nitade Chula
Online Training @ Nitade ChulaOnline Training @ Nitade Chula
Online Training @ Nitade Chula
 
Subsalt Steep Dip Imaging Study with 3D Acoustic Modeling
Subsalt Steep Dip Imaging Study  with 3D Acoustic  ModelingSubsalt Steep Dip Imaging Study  with 3D Acoustic  Modeling
Subsalt Steep Dip Imaging Study with 3D Acoustic Modeling
 
2015 Tech Predictions
2015 Tech Predictions2015 Tech Predictions
2015 Tech Predictions
 
Mirsis Autocontrol İç Kontrol Yönetimi
Mirsis Autocontrol İç Kontrol YönetimiMirsis Autocontrol İç Kontrol Yönetimi
Mirsis Autocontrol İç Kontrol Yönetimi
 

Similar a Dagger for dummies

Google Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification GoogleGoogle Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification GoogleMathias Seguy
 
Testable Android Apps using data binding and MVVM
Testable Android Apps using data binding and MVVMTestable Android Apps using data binding and MVVM
Testable Android Apps using data binding and MVVMFabio Collini
 
Building maintainable app #droidconzg
Building maintainable app #droidconzgBuilding maintainable app #droidconzg
Building maintainable app #droidconzgKristijan Jurković
 
It's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journeyIt's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journeyThiago “Fred” Porciúncula
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2Javad Hashemi
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014First Tuesday Bergen
 
Microservices Architecture: Labs
Microservices Architecture: LabsMicroservices Architecture: Labs
Microservices Architecture: Labsgjuljo
 
Building a Native Camera Access Library - Part II.pdf
Building a Native Camera Access Library - Part II.pdfBuilding a Native Camera Access Library - Part II.pdf
Building a Native Camera Access Library - Part II.pdfShaiAlmog1
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Python Ireland
 
Avoiding and dealing with conflicting updates in Oak
Avoiding and dealing with conflicting updates in OakAvoiding and dealing with conflicting updates in Oak
Avoiding and dealing with conflicting updates in Oakmichid
 
Using and contributing to the next Guice
Using and contributing to the next GuiceUsing and contributing to the next Guice
Using and contributing to the next GuiceAdrian Cole
 
JSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan ZarnikovJSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan ZarnikovChristoph Pickl
 

Similar a Dagger for dummies (20)

guice-servlet
guice-servletguice-servlet
guice-servlet
 
Google Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification GoogleGoogle Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification Google
 
Google GIN
Google GINGoogle GIN
Google GIN
 
Testable Android Apps using data binding and MVVM
Testable Android Apps using data binding and MVVMTestable Android Apps using data binding and MVVM
Testable Android Apps using data binding and MVVM
 
Building maintainable app #droidconzg
Building maintainable app #droidconzgBuilding maintainable app #droidconzg
Building maintainable app #droidconzg
 
SOLID
SOLIDSOLID
SOLID
 
It's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journeyIt's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journey
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
 
Building maintainable app
Building maintainable appBuilding maintainable app
Building maintainable app
 
Microservices Architecture: Labs
Microservices Architecture: LabsMicroservices Architecture: Labs
Microservices Architecture: Labs
 
Building a Native Camera Access Library - Part II.pdf
Building a Native Camera Access Library - Part II.pdfBuilding a Native Camera Access Library - Part II.pdf
Building a Native Camera Access Library - Part II.pdf
 
Solid angular
Solid angularSolid angular
Solid angular
 
從零開始學 Android
從零開始學 Android從零開始學 Android
從零開始學 Android
 
Popup view on Mortar
Popup view on MortarPopup view on Mortar
Popup view on Mortar
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)
 
Avoiding and dealing with conflicting updates in Oak
Avoiding and dealing with conflicting updates in OakAvoiding and dealing with conflicting updates in Oak
Avoiding and dealing with conflicting updates in Oak
 
Using and contributing to the next Guice
Using and contributing to the next GuiceUsing and contributing to the next Guice
Using and contributing to the next Guice
 
JSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan ZarnikovJSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan Zarnikov
 

Último

Large Scale Architecture -- The Unreasonable Effectiveness of Simplicity
Large Scale Architecture -- The Unreasonable Effectiveness of SimplicityLarge Scale Architecture -- The Unreasonable Effectiveness of Simplicity
Large Scale Architecture -- The Unreasonable Effectiveness of SimplicityRandy Shoup
 
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...Maxim Salnikov
 
Practical Advice for FDA’s 510(k) Requirements.pdf
Practical Advice for FDA’s 510(k) Requirements.pdfPractical Advice for FDA’s 510(k) Requirements.pdf
Practical Advice for FDA’s 510(k) Requirements.pdfICS
 
VuNet software organisation powerpoint deck
VuNet software organisation powerpoint deckVuNet software organisation powerpoint deck
VuNet software organisation powerpoint deckNaval Singh
 
Boost Efficiency: Sabre API Integration Made Easy
Boost Efficiency: Sabre API Integration Made EasyBoost Efficiency: Sabre API Integration Made Easy
Boost Efficiency: Sabre API Integration Made Easymichealwillson701
 
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...jackiepotts6
 
BusinessGPT - SECURITY AND GOVERNANCE FOR GENERATIVE AI.pptx
BusinessGPT  - SECURITY AND GOVERNANCE  FOR GENERATIVE AI.pptxBusinessGPT  - SECURITY AND GOVERNANCE  FOR GENERATIVE AI.pptx
BusinessGPT - SECURITY AND GOVERNANCE FOR GENERATIVE AI.pptxAGATSoftware
 
8 key point on optimizing web hosting services in your business.pdf
8 key point on optimizing web hosting services in your business.pdf8 key point on optimizing web hosting services in your business.pdf
8 key point on optimizing web hosting services in your business.pdfOffsiteNOC
 
Mobile App Development process | Expert Tips
Mobile App Development process | Expert TipsMobile App Development process | Expert Tips
Mobile App Development process | Expert Tipsmichealwillson701
 
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdfFlutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdfMind IT Systems
 
User Experience Designer | Kaylee Miller Resume
User Experience Designer | Kaylee Miller ResumeUser Experience Designer | Kaylee Miller Resume
User Experience Designer | Kaylee Miller ResumeKaylee Miller
 
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptxCYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptxBarakaMuyengi
 
MUT4SLX: Extensions for Mutation Testing of Stateflow Models
MUT4SLX: Extensions for Mutation Testing of Stateflow ModelsMUT4SLX: Extensions for Mutation Testing of Stateflow Models
MUT4SLX: Extensions for Mutation Testing of Stateflow ModelsUniversity of Antwerp
 
Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...
Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...
Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...MyFAA
 
BATbern52 Swisscom's Journey into Data Mesh
BATbern52 Swisscom's Journey into Data MeshBATbern52 Swisscom's Journey into Data Mesh
BATbern52 Swisscom's Journey into Data MeshBATbern
 
Unlocking AI: Navigating Open Source vs. Commercial Frontiers
Unlocking AI:Navigating Open Source vs. Commercial FrontiersUnlocking AI:Navigating Open Source vs. Commercial Frontiers
Unlocking AI: Navigating Open Source vs. Commercial FrontiersRaphaël Semeteys
 
renewable energy renewable energy renewable energy renewable energy
renewable energy renewable energy renewable energy  renewable energyrenewable energy renewable energy renewable energy  renewable energy
renewable energy renewable energy renewable energy renewable energyjeyasrig
 
Enterprise Content Managements Solutions
Enterprise Content Managements SolutionsEnterprise Content Managements Solutions
Enterprise Content Managements SolutionsIQBG inc
 
Technical improvements. Reasons. Methods. Estimations. CJ
Technical improvements.  Reasons. Methods. Estimations. CJTechnical improvements.  Reasons. Methods. Estimations. CJ
Technical improvements. Reasons. Methods. Estimations. CJpolinaucc
 
Unlocking the Power of IoT: A comprehensive approach to real-time insights
Unlocking the Power of IoT: A comprehensive approach to real-time insightsUnlocking the Power of IoT: A comprehensive approach to real-time insights
Unlocking the Power of IoT: A comprehensive approach to real-time insightsconfluent
 

Último (20)

Large Scale Architecture -- The Unreasonable Effectiveness of Simplicity
Large Scale Architecture -- The Unreasonable Effectiveness of SimplicityLarge Scale Architecture -- The Unreasonable Effectiveness of Simplicity
Large Scale Architecture -- The Unreasonable Effectiveness of Simplicity
 
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
 
Practical Advice for FDA’s 510(k) Requirements.pdf
Practical Advice for FDA’s 510(k) Requirements.pdfPractical Advice for FDA’s 510(k) Requirements.pdf
Practical Advice for FDA’s 510(k) Requirements.pdf
 
VuNet software organisation powerpoint deck
VuNet software organisation powerpoint deckVuNet software organisation powerpoint deck
VuNet software organisation powerpoint deck
 
Boost Efficiency: Sabre API Integration Made Easy
Boost Efficiency: Sabre API Integration Made EasyBoost Efficiency: Sabre API Integration Made Easy
Boost Efficiency: Sabre API Integration Made Easy
 
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
 
BusinessGPT - SECURITY AND GOVERNANCE FOR GENERATIVE AI.pptx
BusinessGPT  - SECURITY AND GOVERNANCE  FOR GENERATIVE AI.pptxBusinessGPT  - SECURITY AND GOVERNANCE  FOR GENERATIVE AI.pptx
BusinessGPT - SECURITY AND GOVERNANCE FOR GENERATIVE AI.pptx
 
8 key point on optimizing web hosting services in your business.pdf
8 key point on optimizing web hosting services in your business.pdf8 key point on optimizing web hosting services in your business.pdf
8 key point on optimizing web hosting services in your business.pdf
 
Mobile App Development process | Expert Tips
Mobile App Development process | Expert TipsMobile App Development process | Expert Tips
Mobile App Development process | Expert Tips
 
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdfFlutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
 
User Experience Designer | Kaylee Miller Resume
User Experience Designer | Kaylee Miller ResumeUser Experience Designer | Kaylee Miller Resume
User Experience Designer | Kaylee Miller Resume
 
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptxCYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
 
MUT4SLX: Extensions for Mutation Testing of Stateflow Models
MUT4SLX: Extensions for Mutation Testing of Stateflow ModelsMUT4SLX: Extensions for Mutation Testing of Stateflow Models
MUT4SLX: Extensions for Mutation Testing of Stateflow Models
 
Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...
Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...
Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...
 
BATbern52 Swisscom's Journey into Data Mesh
BATbern52 Swisscom's Journey into Data MeshBATbern52 Swisscom's Journey into Data Mesh
BATbern52 Swisscom's Journey into Data Mesh
 
Unlocking AI: Navigating Open Source vs. Commercial Frontiers
Unlocking AI:Navigating Open Source vs. Commercial FrontiersUnlocking AI:Navigating Open Source vs. Commercial Frontiers
Unlocking AI: Navigating Open Source vs. Commercial Frontiers
 
renewable energy renewable energy renewable energy renewable energy
renewable energy renewable energy renewable energy  renewable energyrenewable energy renewable energy renewable energy  renewable energy
renewable energy renewable energy renewable energy renewable energy
 
Enterprise Content Managements Solutions
Enterprise Content Managements SolutionsEnterprise Content Managements Solutions
Enterprise Content Managements Solutions
 
Technical improvements. Reasons. Methods. Estimations. CJ
Technical improvements.  Reasons. Methods. Estimations. CJTechnical improvements.  Reasons. Methods. Estimations. CJ
Technical improvements. Reasons. Methods. Estimations. CJ
 
Unlocking the Power of IoT: A comprehensive approach to real-time insights
Unlocking the Power of IoT: A comprehensive approach to real-time insightsUnlocking the Power of IoT: A comprehensive approach to real-time insights
Unlocking the Power of IoT: A comprehensive approach to real-time insights
 

Dagger for dummies

  • 1. ABUSING DEPENDENCY INJECTION WITH DAGGER FOR DUMMIES Saúl Díaz (@sefford) Freakend ‘15
  • 2. new Flipper(new Gintonic(new Gin(new Alcohol()))) FlipperGintonic GinAlcohol
  • 3. SHOULD I USE DI WITH MY PERSONAL/PRO PROJECT?
  • 6. @Module( includes = RosieModule.class, addsTo = {AndroidModule.class, DrinkModule.class, CodingModule.class } injects = FlipperFragment.class, complete = true, ) public class FlipperModule { @Provides @Named(“Tuenti”) public FlipperInterface provideFlipper(Gintonic drink, Trolling trolling, Android android) { return new FlipperImpl(drink, trolling, android); } }
  • 7. public class FlipperFragment extends Fragment { ObjectGraph graph; @Inject FlipperInterface flipper; @Override public void onCreate(Bundle bundle) { graph = ObjectGraph.create(new FlipperModule()); graph.inject(this); FlipperInterface flipper2 = graph.get(Flipper.class); }
  • 8. IDSPISPOPD FOR SINGLETONS @Singleton ● By definition, Singletons cannot be tested ● Provides same instance of class for Graph ● This instance is not static
  • 10. Lazy<Flipper> lazyFlipper; ● Creates the instance on lazyFlipper.get() ● Returns always the same instance (d’oh) ● Always done in UIThread! LAZY INITIALIZATIONS
  • 11. PROVIDING INSTANCES Provider<Flipper> flipperProvider; ● Can help building your own Flipper army ● Returns a different instance each time
  • 12. @Module( override = true; injects = FlipperFragment.class, complete = true, ) public class FlipperTestModule { @Provides @Singleton public FlipperInterface provideFlipper() { return mock(FlipperInterface.class); } } MOCKING INSTANCES
  • 13. DYNAMIC (SCOPED) INJECTION public ObjectGraph extend() { return graph.plus(new ExtensionModule1(), new ExtensionModule2()); }
  • 14. STATIC INJECTION ● Reduce boilerplate and mantenibility by annotating classes and constructions ● Compilation-validated graph
  • 15. SCOPED INJECTION ● Using a SOLID approach, change implementations on runtime ● Graph runtime, validated ● Risk of “BOOOOOOM”
  • 17. CLASSIC EXAMPLE @Module(injects = LoginActivity.class, addsTo = AppModule.class) // @author Antonio Leiva public class LoginModule { private LoginView view; public LoginModule(LoginView view) { this.view = view; } @Provides @Singleton public LoginView provideView() { return view; } @Provides @Singleton public LoginPresenter providePresenter(LoginView loginView, LoginInteractor loginInteractor) { return new LoginPresenterImpl(loginView, loginInteractor); } }
  • 18. WHY STOPPING THERE?public class NoNfcModule() { @Provides public NfcInterfaceController provideNfcController() { return new NullNfcController(); } } public class NfcModule() { @Provides public NfcInterfaceController provideNfcController( NfcAdapter adapter) { return new NfcController(adapter); } }
  • 19. // This goes on Api15Module @Provides @Singleton public StatusBarControllerInterface provideStatusBarControllerInterface() { return new StatusBarAPI15Controller(); } // This goes on Api19Module @Provides @Singleton public StatusBarControllerInterface provideStatusBarControllerInterface() { return new StatusBarAPI19Controller(); } // This goes on Api21Module @Provides @Singleton public StatusBarControllerInterface provideStatusBarControllerInterface() { return new StatusBarAPI21Controller(); }
  • 20. ONE MORE CUP OF ABUSEpublic class ActiveProfileModule() { @Provides public ProfilePresenterInterface provideProfilePres(...) { return new ActiveProfilePresenter(basePresenter,...); } } public class RegularProfileModule() { @Provides public ProfilePresenterInterface provideProfilePres(...) { return new RegularProfilePresenter(basePresenter,...); } }