SlideShare a Scribd company logo
1 of 74
(With Dagger2)
Dependency Injection
Hi There!
● Software Developer for three years
○ Medical Research
○ eCommerce
● Android Developer at heart and profession
● Software Developer at Gett
Game Plan*
●What’s in it for me?
●Dependency Injection Principles
●Dagger2
*To the best of our ability :)
What’s in it for me?
●Testable Code
○ “If I were to plug this code somewhere else, is it guaranteed to work the same
way?”
●Maintainable Code
○ “How many ‘what the..’ moments am I having while reading this code?”
Testable And Maintainable Code?
public class SomeClass {
private SomeOtherClass someOtherClass;
public SomeClass() {
someOtherClass = new SomeOtherClass;
}
}
Testable And Maintainable Code!
public class Customer {
private Breakfast breakfast;
public Customer(Breakfast breakfast) {
this.breakfast = breakfast;
}
}
Game Plan
●What’s in it for me?
●Dependency Injection Principles
●Dagger2
Breakfast!
Breakfast!
Breakfast
Coffee OmeletteBreadJuice Salad
Water SugarMilk VeggiesSaltEggs Olive OilFruit
What is a Dependency?
●A state in which an object uses a function of another object
○ Class A is dependent on class B if and only if A needs B in order to function
●Defined by “import” statements
So how do we use dependencies?
So how do we use dependencies?
●new statements
○ this.breakfast = new Breakfast();
●Singleton objects
○ this.breakfast = Breakfast.getInstance();
●Through constructors and methods
○ this.breakfast = breakfastParameter;
●Inversion Of Control
What is Dependency Injection?
●A technique whereby one object supplies the dependencies of
another object (wikipedia)
●A technique whereby one object supplies the dependencies of
another object (wikipedia)
●There are many ways to do it
○ We just saw four ways!
●DI acronym
Ready for some extremely difficult code?
Extremely difficult code ahead!
// Constructor
public Customer(Breakfast breakfast) {
// Save the reference to the dependency as passed in by the creator
this.mBreakfast = breakfast;
}
// Setter Method
public void setBreakfast(Breakfast breakfast) {
// Save the reference to the dependency as passed in by the creator
this.mBreakfast = breakfast;
}
Okay great, can we go now?
Just one question
How should we create our Breakfast object?
How do we create a breakfast object?
// .. Some code above
Breakfast breakfast = new Breakfast(
new Coffee(
// Dependencies go here..
), new Juice(
// Dependencies go here..
// Some more initializations
);
// Give the client their breakfast
How do we create a breakfast object?
// .. Some code above
Breakfast breakfast = new Breakfast(
new BlackCoffee(Coffee(
// Dependencies go here..
), new Juice(
// Dependencies go here..
// Some more initializations
);
// Give the client their breakfast
How do we create a breakfast object?
// .. Some code above
Breakfast breakfast = new Breakfast(
new BlackCoffee(Coffee(
new Sugarless,
new Skimlesss(new Milk()
// Dependencies go here..
), new Juice(
// Dependencies go here..
// Some more initializations
);
// Give the client their breakfast
Some questions to consider
●What if Breakfast is a supertype of other breakfast types?
○ Factories could work
●What if Breakfast is a singleton in the system?
○ Sure, but singletons are difficult to test
●Can we share breakfast instances with different clients?
○ Kind of, but it’s difficult to maintain
Dependency Injection - A Technique
●A technique whereby one object supplies the dependencies of
another object (wikipedia)
●Just like breakfast, I could do it myself
●But sometimes I want a restaurant to do it for me
○ Because I’m lazy
○ Because they make it better
○ [Insert whatever reason you want here]
Examples
Game Plan*
●Purpose
●Dependency Injection Principles
●Dagger2
*To the best of our ability :)
Why Dagger2?
●Designed for low-end devices
●Generates new code in your application
○ No Reflection
How Do Restaurants Work?
How Does Dagger2 Work?
Modules Component Clients
Module - The Supplier
●Goal
○ Provides dependencies
○ Providing your dependencies context
Modules At A High Level
●A supplier supplies materials
●It declares what it supplies as a contract
○ The restaurant can only get what the supplier supplies
●May depend on material it can supply
●May depend on material it cannot supply
BreakfastSupplierModule example
@Module
public class BreakfastSupplierModule {
@Provides
Omelette provideOmelette(Eggs eggs) { // The eggs will be supplied from the method below
return new ScrambledOmelette();
}
@Provides
Coffee provideCoffee() { // Method name does not matter
return new BlackCoffee();
}
@Provides
Eggs provideEggs() {
return new Eggs();
}
}
Modules - Some FAQ
●Unless stated otherwise
○ The module recreates each object it provides
○ Read on @Singleton for single-instance
●May depend on other module’s dependencies
●May depend on its own dependencies
Components - The Restaurants
●Goal
○ Bridges between the suppliers and the customers
○ Handles the final touches of the “basic materials”
Components At a High Level
●Gathers all of the ingredients from all its suppliers
●Serves a defined set of customers
RestaurantComponent example
@Component(modules = {BreakfastSupplierModule.class})
public interface RestaurantComponent {
// injection methods
void inject(Customer aCustomer);
}
Client Classes
●Use the @Inject annotation to get what they need
●Are supplied through the component
@Inject example
public class Customer {
@Inject Omelette omelette;
@Inject Coffee coffee;
// More code goes here...
}
And Now we “Build”
Component Usage
●The customer depends on the component
●The customer asks the component to serve itself
Component Usage - One way
@Inject Omellete omelette;
@Inject Coffee coffee;
public Customer()
DaggerRestaurantComponent.builder()
.build().breakfastSupplierModule(new BreakfastSupplierModule)
.inject(this);
}
Component Usage - Better way
@Inject Omellete omelette;
@Inject Coffee coffee;
public Customer(BreakfastSupplierModule breakfastModule) {
DaggerRestaurantComponent.builder()
.build().breakfastSupplierModule(breakfastModule)
.inject(this);
}
Component Usage - Dagger Master Way
@Inject Omellete omelette;
@Inject Coffee coffee;
public Customer(RestaurantComponent restaurantComponent) {
restaurantComponent.inject(this);
}
Best Practices
Dos and Don’ts
Don’t @Inject constructor
You don’t know where you’ll find yourself
Seriously… Just don’t use @Inject constructor...
Law of Demeter
Don’t talk to strangers
Don’t!
public class MenuManager {
private SharedPreferences sharedPreferences;
public MenuManager(Context context) {
this.sharedPreferences = context.getSharedPreferences(PREFERENCES_NAME,
Context.MODE_PRIVATE);
}
}
Do!
public class MenuManager {
private SharedPreferences sharedPreferences;
public MenuManager(SharedPreferences sharedPreferences) {
this.sharedPreferences = sharedPreferences;
}
}
Verdict
●Testing is difficult
●Context can do too much for its own good
●I can just pass the SharedPreferences, right?
The client should just reflect its API through
its dependencies
Constructor Injection
My dependencies are created before me, and my creation can still be controlled
Don’t!
public class Customer {
// Another Way simply initialize
public Customer() {
this.breakfast = new Breakfast();
}
}
Don’t!
public class Customer {
// One Way - Inject through component
@Inject Breakfast breakfast;
}
Do!
public class Customer {
private Breakfast breakfast;
public SomeClient(Breakfast breakfast) {
mSomeService = someService;
}
}
Verdict
●Difficult to test
●Client does not reflect its API
●What if Breakfast has dependencies?
If we can create the object on our own, we’ll
just pass the dependencies through the
Constructor
Setter Method Injection
My dependencies are created after me, but my creation can still be controlled
Don’t!
public class MenuView extends LinearLayout {
// Another Way
public Breakfast() {
breakfast = new Breakfast()
}
}
Don’t!
public class MenuView extends LinearLayout {
// One Way
@Inject Breakfast breakfast;
}
Kind of works, but not really...
public class MenuView extends LinearLayout {
public MenuView(Context context, Breakfast breakfast) {
this.breakfast = breakfast;
}
}
Do!
public class MenuView extends LinearLayout {
private Breakfast breakfast;
public void setBreakfast(Breakfast breakfast) {
this.breakfast = breakfast;
}
}
Verdict
●Difficult to test
●View does not reflect its API
●What if Breakfast has dependencies?
●Usage may be limited
If the object may be created by the system,
and not us, but we have access to it through
a pointer, we’ll use setter methods to inject
dependencies
@Inject for Framework Components
The user can’t create me, and can only use me
Don’t!
public class BreakfastActivity extends AppCompatActivity {
private Breakfast breakfast;
public void onCreate(Bundle savedInstanceState) {
this.breakfast = new Breakfast(savedInstanceState);
}
}
Do!
public class BreakfastActivity extends AppCompatActivity {
@Inject Breakfast breakfast;
public SomeClient() {
getActivityComponent().inject(this);
}
}
Verdict
●System components are only interactable through callbacks
○ We cannot hold references to them, or create them
●Use @Inject to declare their needed dependencies
●Use statically created components to inject them
○ Testability comes through modules
○ Testability comes through extension (TestableObject <- Object)
If the object may only be created by the
system, and we may not reference it, we’ll
use dagger’s @Inject feature
Other Tips
●Look at the generated code
○ It’s code that is added to your application
●Use separate @Modules for each feature
○ Modules are classes that can be constructed
○ Provide clarity and customization
BreakfastSupplierModule - Broken Up
@Module
public class OmeletteModule {
@Provides
Omelette provideOmelette(Eggs eggs) { // The eggs will be supplied from
the method below
return new ScrambledOmelette();
}
@Provides
Eggs provideEggs() {
return new Eggs();
}
}
BreakfastSupplierModule - Broken Up
@Module
public class CoffeeModule {
@Provides
Omelette provideCoffee() {
return new BlackCoffee();
}
}
RestaurantComponent Result
@Component(modules = {OmeletteModule.class, CoffeeModule.class})
public interface RestaurantComponent {
// injection methods
void inject(Customer aCustomer);
}
Other Tips
●Look at the generated code
○ It’s code that is added to your application
●Use separate @Modules for each feature● Read on Dagger2’s many (many) features
● Kotlin users beware
Thank yous
●https://www.techyourchance.com
○ Inspiration, ideas and overall thank yous
Thank you

More Related Content

What's hot

Apigility – Lightning Fast API Development - OSSCamp 2014
Apigility – Lightning Fast API Development - OSSCamp 2014 Apigility – Lightning Fast API Development - OSSCamp 2014
Apigility – Lightning Fast API Development - OSSCamp 2014 OSSCube
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2Knoldus Inc.
 
Crystal clear service interfaces w/ Swagger/OpenAPI
Crystal clear service interfaces w/ Swagger/OpenAPICrystal clear service interfaces w/ Swagger/OpenAPI
Crystal clear service interfaces w/ Swagger/OpenAPIScott Triglia
 
Tech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new frameworkTech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new frameworkCodemotion
 
React Native Workshop - React Alicante
React Native Workshop - React AlicanteReact Native Workshop - React Alicante
React Native Workshop - React AlicanteIgnacio Martín
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java DevelopersYakov Fain
 
Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training Patrick Schroeder
 
XebiConFr 15 - Brace yourselves Angular 2 is coming
XebiConFr 15 - Brace yourselves Angular 2 is comingXebiConFr 15 - Brace yourselves Angular 2 is coming
XebiConFr 15 - Brace yourselves Angular 2 is comingPublicis Sapient Engineering
 
Intro To React Native
Intro To React NativeIntro To React Native
Intro To React NativeFITC
 
Come and Play! with Java EE 7
Come and Play! with Java EE 7Come and Play! with Java EE 7
Come and Play! with Java EE 7Antonio Goncalves
 
Angular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersAngular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersOswald Campesato
 
Using Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture projectUsing Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture projectFabio Collini
 
Docker - An Introduction
Docker - An IntroductionDocker - An Introduction
Docker - An IntroductionKnoldus Inc.
 
React Native for ReactJS Devs
React Native for ReactJS DevsReact Native for ReactJS Devs
React Native for ReactJS DevsBarak Cohen
 
Angular 2 : le réveil de la force
Angular 2 : le réveil de la forceAngular 2 : le réveil de la force
Angular 2 : le réveil de la forceNicolas PENNEC
 
React Native: React Meetup 3
React Native: React Meetup 3React Native: React Meetup 3
React Native: React Meetup 3Rob Gietema
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next FrameworkCommit University
 
A gently introduction to AngularJS
A gently introduction to AngularJSA gently introduction to AngularJS
A gently introduction to AngularJSGregor Woiwode
 
Quick run in with Swagger
Quick run in with SwaggerQuick run in with Swagger
Quick run in with SwaggerMesh Korea
 

What's hot (20)

Apigility – Lightning Fast API Development - OSSCamp 2014
Apigility – Lightning Fast API Development - OSSCamp 2014 Apigility – Lightning Fast API Development - OSSCamp 2014
Apigility – Lightning Fast API Development - OSSCamp 2014
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
Crystal clear service interfaces w/ Swagger/OpenAPI
Crystal clear service interfaces w/ Swagger/OpenAPICrystal clear service interfaces w/ Swagger/OpenAPI
Crystal clear service interfaces w/ Swagger/OpenAPI
 
Tech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new frameworkTech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new framework
 
React Native Workshop - React Alicante
React Native Workshop - React AlicanteReact Native Workshop - React Alicante
React Native Workshop - React Alicante
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java Developers
 
Ant User Guide
Ant User GuideAnt User Guide
Ant User Guide
 
Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training
 
XebiConFr 15 - Brace yourselves Angular 2 is coming
XebiConFr 15 - Brace yourselves Angular 2 is comingXebiConFr 15 - Brace yourselves Angular 2 is coming
XebiConFr 15 - Brace yourselves Angular 2 is coming
 
Intro To React Native
Intro To React NativeIntro To React Native
Intro To React Native
 
Come and Play! with Java EE 7
Come and Play! with Java EE 7Come and Play! with Java EE 7
Come and Play! with Java EE 7
 
Angular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersAngular1x and Angular 2 for Beginners
Angular1x and Angular 2 for Beginners
 
Using Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture projectUsing Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture project
 
Docker - An Introduction
Docker - An IntroductionDocker - An Introduction
Docker - An Introduction
 
React Native for ReactJS Devs
React Native for ReactJS DevsReact Native for ReactJS Devs
React Native for ReactJS Devs
 
Angular 2 : le réveil de la force
Angular 2 : le réveil de la forceAngular 2 : le réveil de la force
Angular 2 : le réveil de la force
 
React Native: React Meetup 3
React Native: React Meetup 3React Native: React Meetup 3
React Native: React Meetup 3
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next Framework
 
A gently introduction to AngularJS
A gently introduction to AngularJSA gently introduction to AngularJS
A gently introduction to AngularJS
 
Quick run in with Swagger
Quick run in with SwaggerQuick run in with Swagger
Quick run in with Swagger
 

Similar to Dagger2 Dependency Injection

Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andevMike Nakhimovich
 
Testing android apps with espresso
Testing android apps with espressoTesting android apps with espresso
Testing android apps with espressoÉdipo Souza
 
Getting big without getting fat, in perl
Getting big without getting fat, in perlGetting big without getting fat, in perl
Getting big without getting fat, in perlDean Hamstead
 
Java onguice20070426
Java onguice20070426Java onguice20070426
Java onguice20070426Ratul Ray
 
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017Ortus Solutions, Corp
 
Android Lollipop internals and inferiority complex droidcon.hr 2015
Android Lollipop internals and inferiority complex droidcon.hr 2015 Android Lollipop internals and inferiority complex droidcon.hr 2015
Android Lollipop internals and inferiority complex droidcon.hr 2015 Aleksander Piotrowski
 
Creating Extensible Plugins for WordPress
Creating Extensible Plugins for WordPressCreating Extensible Plugins for WordPress
Creating Extensible Plugins for WordPressHristo Chakarov
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2Javad Hashemi
 
Dependency injection using Google guice
Dependency injection using Google guiceDependency injection using Google guice
Dependency injection using Google guiceAman Verma
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF SummitOrtus Solutions, Corp
 
3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API - 3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API - Ortus Solutions, Corp
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION APIGavin Pickin
 
DotNet unit testing training
DotNet unit testing trainingDotNet unit testing training
DotNet unit testing trainingTom Tang
 
Unit Testing in iOS - Ninjava Talk
Unit Testing in iOS - Ninjava TalkUnit Testing in iOS - Ninjava Talk
Unit Testing in iOS - Ninjava TalkLong Weekend LLC
 
Dependency injection with dagger 2
Dependency injection with dagger 2Dependency injection with dagger 2
Dependency injection with dagger 2Nischal0101
 
Analysing in depth work manager
Analysing in depth work managerAnalysing in depth work manager
Analysing in depth work managerlpu
 
Android 5.0 internals and inferiority complex droidcon.de 2015
Android 5.0 internals and inferiority complex droidcon.de 2015Android 5.0 internals and inferiority complex droidcon.de 2015
Android 5.0 internals and inferiority complex droidcon.de 2015Aleksander Piotrowski
 

Similar to Dagger2 Dependency Injection (20)

Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andev
 
Testing android apps with espresso
Testing android apps with espressoTesting android apps with espresso
Testing android apps with espresso
 
Getting big without getting fat, in perl
Getting big without getting fat, in perlGetting big without getting fat, in perl
Getting big without getting fat, in perl
 
Java onguice20070426
Java onguice20070426Java onguice20070426
Java onguice20070426
 
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
 
Android Lollipop internals and inferiority complex droidcon.hr 2015
Android Lollipop internals and inferiority complex droidcon.hr 2015 Android Lollipop internals and inferiority complex droidcon.hr 2015
Android Lollipop internals and inferiority complex droidcon.hr 2015
 
Creating Extensible Plugins for WordPress
Creating Extensible Plugins for WordPressCreating Extensible Plugins for WordPress
Creating Extensible Plugins for WordPress
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2
 
Frontend training
Frontend trainingFrontend training
Frontend training
 
Dependency injection using Google guice
Dependency injection using Google guiceDependency injection using Google guice
Dependency injection using Google guice
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
 
unit_tests_tutorial
unit_tests_tutorialunit_tests_tutorial
unit_tests_tutorial
 
3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API - 3 WAYS TO TEST YOUR COLDFUSION API -
3 WAYS TO TEST YOUR COLDFUSION API -
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API
 
DotNet unit testing training
DotNet unit testing trainingDotNet unit testing training
DotNet unit testing training
 
Unit Testing in iOS - Ninjava Talk
Unit Testing in iOS - Ninjava TalkUnit Testing in iOS - Ninjava Talk
Unit Testing in iOS - Ninjava Talk
 
Dagger 2, 2 years later
Dagger 2, 2 years laterDagger 2, 2 years later
Dagger 2, 2 years later
 
Dependency injection with dagger 2
Dependency injection with dagger 2Dependency injection with dagger 2
Dependency injection with dagger 2
 
Analysing in depth work manager
Analysing in depth work managerAnalysing in depth work manager
Analysing in depth work manager
 
Android 5.0 internals and inferiority complex droidcon.de 2015
Android 5.0 internals and inferiority complex droidcon.de 2015Android 5.0 internals and inferiority complex droidcon.de 2015
Android 5.0 internals and inferiority complex droidcon.de 2015
 

More from Vitali Pekelis

Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940Vitali Pekelis
 
Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019Vitali Pekelis
 
Advanced #6 clean architecture
Advanced #6  clean architectureAdvanced #6  clean architecture
Advanced #6 clean architectureVitali Pekelis
 
Advanced #4 GPU & Animations
Advanced #4   GPU & AnimationsAdvanced #4   GPU & Animations
Advanced #4 GPU & AnimationsVitali Pekelis
 
Advanced #2 networking
Advanced #2   networkingAdvanced #2   networking
Advanced #2 networkingVitali Pekelis
 
Advanced #1 cpu, memory
Advanced #1   cpu, memoryAdvanced #1   cpu, memory
Advanced #1 cpu, memoryVitali Pekelis
 
Android design patterns
Android design patternsAndroid design patterns
Android design patternsVitali Pekelis
 
Advanced #3 threading
Advanced #3  threading Advanced #3  threading
Advanced #3 threading Vitali Pekelis
 
Mobile ui fruit or delicious sweets
Mobile ui  fruit or delicious sweetsMobile ui  fruit or delicious sweets
Mobile ui fruit or delicious sweetsVitali Pekelis
 
Lecture #4 c loaders and co.
Lecture #4 c   loaders and co.Lecture #4 c   loaders and co.
Lecture #4 c loaders and co.Vitali Pekelis
 
Session #4 b content providers
Session #4 b  content providersSession #4 b  content providers
Session #4 b content providersVitali Pekelis
 
Advanced #2 - ui perf
 Advanced #2 - ui perf Advanced #2 - ui perf
Advanced #2 - ui perfVitali Pekelis
 
Android design lecture #3
Android design   lecture #3Android design   lecture #3
Android design lecture #3Vitali Pekelis
 
Working better together designers &amp; developers
Working better together   designers &amp; developersWorking better together   designers &amp; developers
Working better together designers &amp; developersVitali Pekelis
 
Android material design lecture #2
Android material design   lecture #2Android material design   lecture #2
Android material design lecture #2Vitali Pekelis
 

More from Vitali Pekelis (20)

Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940
 
Droidkaigi 2019
Droidkaigi 2019Droidkaigi 2019
Droidkaigi 2019
 
Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019
 
Android Q 2019
Android Q 2019Android Q 2019
Android Q 2019
 
Advanced #6 clean architecture
Advanced #6  clean architectureAdvanced #6  clean architecture
Advanced #6 clean architecture
 
Advanced #4 GPU & Animations
Advanced #4   GPU & AnimationsAdvanced #4   GPU & Animations
Advanced #4 GPU & Animations
 
Advanced #2 networking
Advanced #2   networkingAdvanced #2   networking
Advanced #2 networking
 
Advanced #2 threading
Advanced #2   threadingAdvanced #2   threading
Advanced #2 threading
 
Advanced #1 cpu, memory
Advanced #1   cpu, memoryAdvanced #1   cpu, memory
Advanced #1 cpu, memory
 
Android design patterns
Android design patternsAndroid design patterns
Android design patterns
 
Advanced #3 threading
Advanced #3  threading Advanced #3  threading
Advanced #3 threading
 
Mobile ui fruit or delicious sweets
Mobile ui  fruit or delicious sweetsMobile ui  fruit or delicious sweets
Mobile ui fruit or delicious sweets
 
Lecture #4 c loaders and co.
Lecture #4 c   loaders and co.Lecture #4 c   loaders and co.
Lecture #4 c loaders and co.
 
Session #4 b content providers
Session #4 b  content providersSession #4 b  content providers
Session #4 b content providers
 
Advanced #2 - ui perf
 Advanced #2 - ui perf Advanced #2 - ui perf
Advanced #2 - ui perf
 
Android meetup
Android meetupAndroid meetup
Android meetup
 
Android design lecture #3
Android design   lecture #3Android design   lecture #3
Android design lecture #3
 
From newbie to ...
From newbie to ...From newbie to ...
From newbie to ...
 
Working better together designers &amp; developers
Working better together   designers &amp; developersWorking better together   designers &amp; developers
Working better together designers &amp; developers
 
Android material design lecture #2
Android material design   lecture #2Android material design   lecture #2
Android material design lecture #2
 

Recently uploaded

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 

Recently uploaded (20)

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 

Dagger2 Dependency Injection

  • 2.
  • 3. Hi There! ● Software Developer for three years ○ Medical Research ○ eCommerce ● Android Developer at heart and profession ● Software Developer at Gett
  • 4. Game Plan* ●What’s in it for me? ●Dependency Injection Principles ●Dagger2 *To the best of our ability :)
  • 5. What’s in it for me? ●Testable Code ○ “If I were to plug this code somewhere else, is it guaranteed to work the same way?” ●Maintainable Code ○ “How many ‘what the..’ moments am I having while reading this code?”
  • 6. Testable And Maintainable Code? public class SomeClass { private SomeOtherClass someOtherClass; public SomeClass() { someOtherClass = new SomeOtherClass; } }
  • 7. Testable And Maintainable Code! public class Customer { private Breakfast breakfast; public Customer(Breakfast breakfast) { this.breakfast = breakfast; } }
  • 8. Game Plan ●What’s in it for me? ●Dependency Injection Principles ●Dagger2
  • 10. Breakfast! Breakfast Coffee OmeletteBreadJuice Salad Water SugarMilk VeggiesSaltEggs Olive OilFruit
  • 11. What is a Dependency? ●A state in which an object uses a function of another object ○ Class A is dependent on class B if and only if A needs B in order to function ●Defined by “import” statements
  • 12. So how do we use dependencies?
  • 13. So how do we use dependencies? ●new statements ○ this.breakfast = new Breakfast(); ●Singleton objects ○ this.breakfast = Breakfast.getInstance(); ●Through constructors and methods ○ this.breakfast = breakfastParameter; ●Inversion Of Control
  • 14. What is Dependency Injection? ●A technique whereby one object supplies the dependencies of another object (wikipedia) ●A technique whereby one object supplies the dependencies of another object (wikipedia) ●There are many ways to do it ○ We just saw four ways! ●DI acronym
  • 15. Ready for some extremely difficult code?
  • 16. Extremely difficult code ahead! // Constructor public Customer(Breakfast breakfast) { // Save the reference to the dependency as passed in by the creator this.mBreakfast = breakfast; } // Setter Method public void setBreakfast(Breakfast breakfast) { // Save the reference to the dependency as passed in by the creator this.mBreakfast = breakfast; }
  • 17. Okay great, can we go now?
  • 18. Just one question How should we create our Breakfast object?
  • 19. How do we create a breakfast object? // .. Some code above Breakfast breakfast = new Breakfast( new Coffee( // Dependencies go here.. ), new Juice( // Dependencies go here.. // Some more initializations ); // Give the client their breakfast
  • 20. How do we create a breakfast object? // .. Some code above Breakfast breakfast = new Breakfast( new BlackCoffee(Coffee( // Dependencies go here.. ), new Juice( // Dependencies go here.. // Some more initializations ); // Give the client their breakfast
  • 21. How do we create a breakfast object? // .. Some code above Breakfast breakfast = new Breakfast( new BlackCoffee(Coffee( new Sugarless, new Skimlesss(new Milk() // Dependencies go here.. ), new Juice( // Dependencies go here.. // Some more initializations ); // Give the client their breakfast
  • 22. Some questions to consider ●What if Breakfast is a supertype of other breakfast types? ○ Factories could work ●What if Breakfast is a singleton in the system? ○ Sure, but singletons are difficult to test ●Can we share breakfast instances with different clients? ○ Kind of, but it’s difficult to maintain
  • 23. Dependency Injection - A Technique ●A technique whereby one object supplies the dependencies of another object (wikipedia) ●Just like breakfast, I could do it myself ●But sometimes I want a restaurant to do it for me ○ Because I’m lazy ○ Because they make it better ○ [Insert whatever reason you want here]
  • 25. Game Plan* ●Purpose ●Dependency Injection Principles ●Dagger2 *To the best of our ability :)
  • 26. Why Dagger2? ●Designed for low-end devices ●Generates new code in your application ○ No Reflection
  • 28. How Does Dagger2 Work? Modules Component Clients
  • 29. Module - The Supplier ●Goal ○ Provides dependencies ○ Providing your dependencies context
  • 30. Modules At A High Level ●A supplier supplies materials ●It declares what it supplies as a contract ○ The restaurant can only get what the supplier supplies ●May depend on material it can supply ●May depend on material it cannot supply
  • 31. BreakfastSupplierModule example @Module public class BreakfastSupplierModule { @Provides Omelette provideOmelette(Eggs eggs) { // The eggs will be supplied from the method below return new ScrambledOmelette(); } @Provides Coffee provideCoffee() { // Method name does not matter return new BlackCoffee(); } @Provides Eggs provideEggs() { return new Eggs(); } }
  • 32. Modules - Some FAQ ●Unless stated otherwise ○ The module recreates each object it provides ○ Read on @Singleton for single-instance ●May depend on other module’s dependencies ●May depend on its own dependencies
  • 33. Components - The Restaurants ●Goal ○ Bridges between the suppliers and the customers ○ Handles the final touches of the “basic materials”
  • 34. Components At a High Level ●Gathers all of the ingredients from all its suppliers ●Serves a defined set of customers
  • 35. RestaurantComponent example @Component(modules = {BreakfastSupplierModule.class}) public interface RestaurantComponent { // injection methods void inject(Customer aCustomer); }
  • 36. Client Classes ●Use the @Inject annotation to get what they need ●Are supplied through the component
  • 37. @Inject example public class Customer { @Inject Omelette omelette; @Inject Coffee coffee; // More code goes here... }
  • 38. And Now we “Build”
  • 39. Component Usage ●The customer depends on the component ●The customer asks the component to serve itself
  • 40. Component Usage - One way @Inject Omellete omelette; @Inject Coffee coffee; public Customer() DaggerRestaurantComponent.builder() .build().breakfastSupplierModule(new BreakfastSupplierModule) .inject(this); }
  • 41. Component Usage - Better way @Inject Omellete omelette; @Inject Coffee coffee; public Customer(BreakfastSupplierModule breakfastModule) { DaggerRestaurantComponent.builder() .build().breakfastSupplierModule(breakfastModule) .inject(this); }
  • 42. Component Usage - Dagger Master Way @Inject Omellete omelette; @Inject Coffee coffee; public Customer(RestaurantComponent restaurantComponent) { restaurantComponent.inject(this); }
  • 44. Don’t @Inject constructor You don’t know where you’ll find yourself Seriously… Just don’t use @Inject constructor...
  • 45. Law of Demeter Don’t talk to strangers
  • 46. Don’t! public class MenuManager { private SharedPreferences sharedPreferences; public MenuManager(Context context) { this.sharedPreferences = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); } }
  • 47. Do! public class MenuManager { private SharedPreferences sharedPreferences; public MenuManager(SharedPreferences sharedPreferences) { this.sharedPreferences = sharedPreferences; } }
  • 48. Verdict ●Testing is difficult ●Context can do too much for its own good ●I can just pass the SharedPreferences, right?
  • 49. The client should just reflect its API through its dependencies
  • 50. Constructor Injection My dependencies are created before me, and my creation can still be controlled
  • 51. Don’t! public class Customer { // Another Way simply initialize public Customer() { this.breakfast = new Breakfast(); } }
  • 52. Don’t! public class Customer { // One Way - Inject through component @Inject Breakfast breakfast; }
  • 53. Do! public class Customer { private Breakfast breakfast; public SomeClient(Breakfast breakfast) { mSomeService = someService; } }
  • 54. Verdict ●Difficult to test ●Client does not reflect its API ●What if Breakfast has dependencies?
  • 55. If we can create the object on our own, we’ll just pass the dependencies through the Constructor
  • 56. Setter Method Injection My dependencies are created after me, but my creation can still be controlled
  • 57. Don’t! public class MenuView extends LinearLayout { // Another Way public Breakfast() { breakfast = new Breakfast() } }
  • 58. Don’t! public class MenuView extends LinearLayout { // One Way @Inject Breakfast breakfast; }
  • 59. Kind of works, but not really... public class MenuView extends LinearLayout { public MenuView(Context context, Breakfast breakfast) { this.breakfast = breakfast; } }
  • 60. Do! public class MenuView extends LinearLayout { private Breakfast breakfast; public void setBreakfast(Breakfast breakfast) { this.breakfast = breakfast; } }
  • 61. Verdict ●Difficult to test ●View does not reflect its API ●What if Breakfast has dependencies? ●Usage may be limited
  • 62. If the object may be created by the system, and not us, but we have access to it through a pointer, we’ll use setter methods to inject dependencies
  • 63. @Inject for Framework Components The user can’t create me, and can only use me
  • 64. Don’t! public class BreakfastActivity extends AppCompatActivity { private Breakfast breakfast; public void onCreate(Bundle savedInstanceState) { this.breakfast = new Breakfast(savedInstanceState); } }
  • 65. Do! public class BreakfastActivity extends AppCompatActivity { @Inject Breakfast breakfast; public SomeClient() { getActivityComponent().inject(this); } }
  • 66. Verdict ●System components are only interactable through callbacks ○ We cannot hold references to them, or create them ●Use @Inject to declare their needed dependencies ●Use statically created components to inject them ○ Testability comes through modules ○ Testability comes through extension (TestableObject <- Object)
  • 67. If the object may only be created by the system, and we may not reference it, we’ll use dagger’s @Inject feature
  • 68. Other Tips ●Look at the generated code ○ It’s code that is added to your application ●Use separate @Modules for each feature ○ Modules are classes that can be constructed ○ Provide clarity and customization
  • 69. BreakfastSupplierModule - Broken Up @Module public class OmeletteModule { @Provides Omelette provideOmelette(Eggs eggs) { // The eggs will be supplied from the method below return new ScrambledOmelette(); } @Provides Eggs provideEggs() { return new Eggs(); } }
  • 70. BreakfastSupplierModule - Broken Up @Module public class CoffeeModule { @Provides Omelette provideCoffee() { return new BlackCoffee(); } }
  • 71. RestaurantComponent Result @Component(modules = {OmeletteModule.class, CoffeeModule.class}) public interface RestaurantComponent { // injection methods void inject(Customer aCustomer); }
  • 72. Other Tips ●Look at the generated code ○ It’s code that is added to your application ●Use separate @Modules for each feature● Read on Dagger2’s many (many) features ● Kotlin users beware

Editor's Notes

  1. Here’s what we’re going to cover
  2. The following is a list of High-Level Concepts in computer science that led to the postulation of Dependency Injection pattern These are guidelines that can actually turn into work ethics. These are still guidelines
  3. Talk about Breakfast metaphor (“Let’s make breakfast”) First you need to create coffee. To do so you need a machine, water, a capsul and milk. Ok great Let’s make eggs. You need a pan, eggs, and maybe salt and pepper. Almost there Let’s make pancakes. You need milk, eggs, batter, and sugar. Let’s make orange juice. For it you just need oranges and sugar. Lastly, let’s cut some veggies. That’s dependency injection at its finest
  4. Talk about Breakfast metaphor (“Let’s make breakfast”) First you need to create coffee. To do so you need a machine, water, a capsul and milk. Ok great Let’s make eggs. You need a pan, eggs, and maybe salt and pepper. Almost there Let’s make pancakes. You need milk, eggs, batter, and sugar. Let’s make orange juice. For it you just need oranges and sugar. Lastly, let’s cut some veggies. That’s dependency injection at its finest
  5. dependency injection is a technique whereby one object supplies the dependencies of another object
  6. There are tons more Note - there are some languages and frameworks that do not need dependency injection frameworks. We use Java, so naturally we need it. (Think about why)
  7. High level description
  8. High level description
  9. High level description
  10. High level description
  11. The names of the methods again don’t matter The target is declared as the parameter of the inject method The modules are declared in the @Component annotation Base classes do not count - we need concrete implementations
  12. The example shows an activity, but this can be done in any class really. Note the Injector class section - we will talk about this in the next slide
  13. I would urge you to take these following tips and tricks with a grain of salt, but from my experience this is what helped me organize my code the best
  14. Client Reflects its api We don’t care what DI Frameworks we use