SlideShare a Scribd company logo
Intro To Dependency Injection
Or Bar
- What is a Dependency?
- Dependency Injection
- Dependency Inversion Principle
- Dependency Injection Frameworks
Agenda
A depends on B
public class Example {

DatabaseHelper mDatabaseHelper;



public Example() {

mDatabaseHelper = new DatabaseHelper();

}



public void doStuff() {

...

mDatabaseHelper.loadUsers();

...

}

}
- Dependency injection is a software design pattern that
implements inversion of control for resolving dependencies
- An injection is the passing of a dependency to a dependent
object to use
public class Example {

DatabaseHelper mDatabaseHelper;



public Example() {

mDatabaseHelper = new DatabaseHelper();

}

}
public class Example {

DatabaseHelper mDatabaseHelper;



public Example() {

mDatabaseHelper = new DatabaseHelper();

}

}
public class Example { 

DatabaseHelper mDatabaseHelper;



public Example(DatabaseHelper databaseHelper) {

mDatabaseHelper = databaseHelper;

}

}
public class Example {

DatabaseHelper mDatabaseHelper;



public Example() {

mDatabaseHelper = new DatabaseHelper();

}

}
public class Example {

DatabaseHelper mDatabaseHelper;
public Example() {

mDatabaseHelper = new DatabaseHelper();

}

}

public class Example { 

DatabaseHelper mDatabaseHelper;



public Example(DatabaseHelper databaseHelper) {

mDatabaseHelper = databaseHelper;

}

}
public class Example {

DatabaseHelper mDatabaseHelper;


public Example(DatabaseHelper databaseHelper) {

mDatabaseHelper = databaseHelper;

}

}

public class Example {

DatabaseHelper mDatabaseHelper;



public Example() {

}



public void setDatabaseHelper(DatabaseHelper databaseHelper) {

mDatabaseHelper = databaseHelper;

}

}
- Shared dependencies
- Configure dependencies externally
- Separation of modules
- Inherent testability
Why?
public class ExampleTest {

@Mock DatabaseHelper mockDatabaseHelper;



@Test

public void testExample_doStuff() {

Example example = new Example(mockDatabaseHelper);

example.doStuff();

mockDatabaseHelper.AssertGetDataWasCalled();

}

}
public class Example { 

DatabaseHelper mDatabaseHelper;



public Example(DatabaseHelper databaseHelper) {

mDatabaseHelper = databaseHelper;

}
public void doStuff() {

...

mDatabaseHelper.loadUsers();

...

}

}
- High-level modules should not depend on low-level modules.
Both should depend on abstractions.
- Abstractions should not depend on details. Details should
depend on abstractions.
Dependency Inversion Principle
A depends on B
A is coupled to B
- Bare bones ebook reader
- Supports PDF files
- Prints book contents to screen
Ebook Reader
CoolEBookReader
PDFReader DisplayPrinter
public class CoolEBookReader {

public void loadPage(String bookUri, int PageNumber) {

String pdfContent = getPdfContent(bookUri, PageNumber);

displayPage(pdfContent);

}
}
public class CoolEBookReader {

enum BookType {

PDF,

EPUB

}



public void loadPage(BookType bookType, String bookUri, int PageNumber) {

String pageContent;

if (bookType == BookType.PDF) {

pageContent = getPdfContent(bookUri, PageNumber);

} else if (bookType == BookType.EPUB) {

pageContent = getEpubContent(bookUri, PageNumber);

} else {

throw new IllegalArgumentException("Unknown book type");

}

displayPage(pageContent); 

}

}
public class CoolEBookReader {

enum BookType {

PDF,

EPUB



}



enum PrinterType {

SCREEN,

VOICE



}



public void loadPage(BookType bookType, PrinterType printerType, String bookUri, int PageNumber) {

String pageContent;

if (bookType == BookType.PDF) {

pageContent = getPdfContent(bookUri, PageNumber);

} else if (bookType == BookType.EPUB) {

pageContent = getEpubContent(bookUri, PageNumber);

} else {

throw new IllegalArgumentException("Unknown book type");

}



if (printerType == PrinterType.SCREEN) {

displayPage(pageContent);

} else if (printerType == PrinterType.VOICE) {

readAloudPage(pageContent);

} else {

throw new IllegalArgumentException("Unknown printer type");

}

}

}
- High-level modules should not depend on low-level modules.
Both should depend on abstractions.
- Abstractions should not depend on details. Details should
depend on abstractions.
Dependency Inversion
CoolEBookReader
PDFReader DisplayPrinter
<<Interface>>
Reader
<<Interface>>
Printer
interface Reader {

String read(String bookUri, int pagNumber);
}



interface Printer {

void print(String pageContent);

}
public class CoolEBookReader {

public void loadPage(Reader reader, Printer printer, String bookUri, int pageNumber) {

String pageContent = reader.read(bookUri, pageNumber);

printer.print(pageContent);

}

}
interface Reader {

String read(String bookUri, int pagNumber);
}



interface Printer {

void print(String pageContent);

}
public class CoolEBookReader {

public void loadPage(Reader reader, Printer printer, String bookUri, int pageNumber) {

String pageContent = reader.read(bookUri, pageNumber);

printer.print(pageContent);

}

}
public class CoolEBookReader {

public void loadPage(String bookUri, int PageNumber) {

String pdfContent = getPdfContent(bookUri, PageNumber);

displayPage(pdfContent);

}
}
public class CoolEBookReaderTest {

@Mock

Reader mockReader;



@Mock

CoolEBookReader.Printer mockPrinter;



@Test 

public void TestExample_loadPage() {

CoolEBookReader coolEBookReader = new CoolEBookReader();

coolEBookReader.loadPage(mockReader, mockPrinter, "", 1);

// Assert Reader.read() is called

// Assert Printer.print() is called

}

}
- Dependency Injection
- Dependency Inversion
- Where are these dependencies come from
What’s next?
- Handles object creation
- Reduces boilerplate code
- A central location for organizing dependencies
- Implement common patterns natively (singleton, lazy loading, etc)
Why use a framework?
- Dagger 1
- Dagger 2
- Guice and RoboGuice
- PicoContainer
- Spring
- Many, many, many, many more options
Common Frameworks
History lesson of DI on Android
- RoboGuice - 2009
- Spring for Android - 2012
- Dagger 1 - 2013
- Dagger 2 - 2015
- Tiger - 2016
- @javax.inject.Inject
- @Module
- @Provides
- @Component
Dagger uses annotations
public class ConnectionHelper {

private Context mContext;



public ConnectionHelper(Context context) {

mContext = context;

}



public boolean isConnected() {

ConnectivityManager connectivityManager =

(ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

return connectivityManager.getActiveNetworkInfo().isConnected();

}

}
ConnectionHelper connectionHelper = new ConnectionHelper(context);



boolean isConnected = connectionHelper.isConnected();
public class ConnectionHelper {

private Context mContext;



@Inject

public ConnectionHelper(Context context) {

mContext = context;

}



public boolean isConnected() {

ConnectivityManager connectivityManager =

(ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);



return connectivityManager.getActiveNetworkInfo().isConnected();

}

}
@Inject
@Module

public class AppModule {



}
@Module
@Provides
@Module

public class AppModule {

private final Context mContext;



public AppModule(Context context) {

mContext = context;

}
@Provides

public Context providesContext() {

return mContext;

}
@Provides

public ConnectionHelper providesConnectionHelper(Context context) {

return new ConnectionHelper(context);

}

}
@Component(modules = {AppModule.class})

public interface AppComponent {



void inject(MainActivity activity);

}
@Component
public class App extends Application {

private AppComponent component;

@Override

public void onCreate() {

super.onCreate();



AppComponent component = DaggerAppComponent.builder()

.appModule(new AppModule(this))

.build();

}



public AppComponent getComponent() {

return component;

}

}
public class App extends Application {

private AppComponent component;

@Override

public void onCreate() {

super.onCreate();



AppComponent component = DaggerAppComponent.builder()

.appModule(new AppModule(this))

.build();

}



public AppComponent getComponent() {

return component;

}

}
public class MainActivity extends AppCompatActivity {



@Inject

ConnectionHelper mConnectionHelper;



@Override

protected void onCreate(Bundle savedInstanceState) {

((App) getApplication()).getComponent().inject(this);



boolean isConnected = mConnectionHelper.isConnected();



textView.setText(isConnected ? "Connected" : "Not Connected");

}

}
public class MainActivity extends AppCompatActivity {



@Inject

ConnectionHelper mConnectionHelper;



@Override

protected void onCreate(Bundle savedInstanceState) {

((App) getApplication()).getComponent().inject(this);



boolean isConnected = mConnectionHelper.isConnected();



textView.setText(isConnected ? "Connected" : "Not Connected");

}

}
@Inject - again
- More annotations
- Scopes
- Lazy injections
- others
Fun stuff
@Provides

@Singleton

public Context providesContext() {

return context;

}
@Singleton
@Singleton

@Component(modules = {AppModule.class})

public interface AppComponent {



void inject(MainActivity activity);
}
@Provides

@Reusable

public ConnectionHelper providesConnectionHelper(Context context) {

return new ConnectionHelper(context);

}
@Reusable
@Singleton
@Reusable

@Component(modules = {AppModule.class})

public interface AppComponent {}
@Inject

Lazy<ConnectionHelper> mConnectionHelper;

...
mConnectionHelper.get().isConnected();
Lazy and Provider Injections
@Inject

Provider<ConnectionHelper> mConnectionHelper;

...
mConnectionHelper.get().isConnected();
@Target(ANNOTATION_TYPE)

@Retention(RUNTIME)

@Documented

public @interface Qualifier {}
@Qualifier
@Qualifier

@Documented

@Retention(RUNTIME)

public @interface Named {}
@Provides
@Singleton
@Named(“Adapter 1”)

public RestAdapter providesRestAdapter1() {
return …;
}
@Qualifier
@Provides
@Singleton
@Named(“Adapter 2”)
public RestAdapter providesRestAdapter2() {
return …;
}
@Qualifier
@Inject
@Named(“Adapter 1”)
RestAdapter mRestAdapter;

Subcomponents and Scopes
- Subcomponents allow you to combine different modules at
runtime
- Scopes let you define the lifetime of a dependency
Testing and dagger
- Constructors used for injections can be used for testing
- Test Modules for espresso
Questions
- @or_bar
- orbar@tumblr.com
- orbar1.tumblr.com

More Related Content

Viewers also liked

Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
Fabien Potencier
 

Viewers also liked (20)

Escaping Dependency Hell v2
Escaping Dependency Hell v2Escaping Dependency Hell v2
Escaping Dependency Hell v2
 
Dependency inversion w php
Dependency inversion w phpDependency inversion w php
Dependency inversion w php
 
Creating killer apps powered by watson cognitive services - Ronen Siman-Tov, IBM
Creating killer apps powered by watson cognitive services - Ronen Siman-Tov, IBMCreating killer apps powered by watson cognitive services - Ronen Siman-Tov, IBM
Creating killer apps powered by watson cognitive services - Ronen Siman-Tov, IBM
 
Android is going to Go! - Android and goland - Almog Baku
Android is going to Go! - Android and goland - Almog BakuAndroid is going to Go! - Android and goland - Almog Baku
Android is going to Go! - Android and goland - Almog Baku
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...Will it run or will it not run? Background processes in Android 6 - Anna Lifs...
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...
 
3 things every Android developer must know about Microsoft - Ido Volff, Micro...
3 things every Android developer must know about Microsoft - Ido Volff, Micro...3 things every Android developer must know about Microsoft - Ido Volff, Micro...
3 things every Android developer must know about Microsoft - Ido Volff, Micro...
 
Engineering Wunderlist for Android - Ceasr Valiente, 6Wunderkinder
Engineering Wunderlist for Android - Ceasr Valiente, 6WunderkinderEngineering Wunderlist for Android - Ceasr Valiente, 6Wunderkinder
Engineering Wunderlist for Android - Ceasr Valiente, 6Wunderkinder
 
Cognitive interaction using Wearables - Eyal herman, IBM
Cognitive interaction using Wearables - Eyal herman, IBMCognitive interaction using Wearables - Eyal herman, IBM
Cognitive interaction using Wearables - Eyal herman, IBM
 
Write code that writes code! A beginner's guide to Annotation Processing - Ja...
Write code that writes code! A beginner's guide to Annotation Processing - Ja...Write code that writes code! A beginner's guide to Annotation Processing - Ja...
Write code that writes code! A beginner's guide to Annotation Processing - Ja...
 
Mobile SDKs: Use with Caution - Ori Lentzitzky
Mobile SDKs: Use with Caution - Ori LentzitzkyMobile SDKs: Use with Caution - Ori Lentzitzky
Mobile SDKs: Use with Caution - Ori Lentzitzky
 
Good Rules for Bad Apps - Shem magnezi
Good Rules for Bad Apps - Shem magnezi Good Rules for Bad Apps - Shem magnezi
Good Rules for Bad Apps - Shem magnezi
 
Context is Everything - Royi Benyossef
Context is Everything - Royi Benyossef Context is Everything - Royi Benyossef
Context is Everything - Royi Benyossef
 
Android Application Optimization: Overview and Tools - Oref Barad, AVG
Android Application Optimization: Overview and Tools - Oref Barad, AVGAndroid Application Optimization: Overview and Tools - Oref Barad, AVG
Android Application Optimization: Overview and Tools - Oref Barad, AVG
 
Set it and forget it: Let the machine learn its job - Guy Baron, Vonage
Set it and forget it: Let the machine learn its job - Guy Baron, VonageSet it and forget it: Let the machine learn its job - Guy Baron, Vonage
Set it and forget it: Let the machine learn its job - Guy Baron, Vonage
 
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 
Knock knock! Who's there? Doze. - Yonatan Levin
Knock knock! Who's there? Doze. - Yonatan Levin Knock knock! Who's there? Doze. - Yonatan Levin
Knock knock! Who's there? Doze. - Yonatan Levin
 
Optimize your delivery and quality with the right release methodology and too...
Optimize your delivery and quality with the right release methodology and too...Optimize your delivery and quality with the right release methodology and too...
Optimize your delivery and quality with the right release methodology and too...
 
Dependency Injection in iOS
Dependency Injection in iOSDependency Injection in iOS
Dependency Injection in iOS
 

Similar to Intro to Dependency Injection - Or bar

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 

Similar to Intro to Dependency Injection - Or bar (20)

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
 
Android Sample Project By Wael Almadhoun
Android Sample Project By Wael AlmadhounAndroid Sample Project By Wael Almadhoun
Android Sample Project By Wael Almadhoun
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017
Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017
Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
 
Architecture components - IT Talk
Architecture components - IT TalkArchitecture components - IT Talk
Architecture components - IT Talk
 
Architecture Components
Architecture Components Architecture Components
Architecture Components
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Design Patterns and Usage
Design Patterns and UsageDesign Patterns and Usage
Design Patterns and Usage
 
Popup view on Mortar
Popup view on MortarPopup view on Mortar
Popup view on Mortar
 
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibility
 
Dependency injection crash course
Dependency injection crash courseDependency injection crash course
Dependency injection crash course
 
Devoxx 2012 (v2)
Devoxx 2012 (v2)Devoxx 2012 (v2)
Devoxx 2012 (v2)
 
Interfaces
InterfacesInterfaces
Interfaces
 
Arquitetando seu app Android com Jetpack
Arquitetando seu app Android com JetpackArquitetando seu app Android com Jetpack
Arquitetando seu app Android com Jetpack
 

More from DroidConTLV

More from DroidConTLV (20)

Mobile Development in the Information Age - Yossi Elkrief, Nike
Mobile Development in the Information Age - Yossi Elkrief, NikeMobile Development in the Information Age - Yossi Elkrief, Nike
Mobile Development in the Information Age - Yossi Elkrief, Nike
 
Doing work in the background - Darryn Campbell, Zebra Technologies
Doing work in the background - Darryn Campbell, Zebra TechnologiesDoing work in the background - Darryn Campbell, Zebra Technologies
Doing work in the background - Darryn Campbell, Zebra Technologies
 
No more video loss - Alex Rivkin, Motorola Solutions
No more video loss - Alex Rivkin, Motorola SolutionsNo more video loss - Alex Rivkin, Motorola Solutions
No more video loss - Alex Rivkin, Motorola Solutions
 
Mobile at Scale: from startup to a big company - Dor Samet, Booking.com
Mobile at Scale: from startup to a big company - Dor Samet, Booking.comMobile at Scale: from startup to a big company - Dor Samet, Booking.com
Mobile at Scale: from startup to a big company - Dor Samet, Booking.com
 
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, ClimacellLiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
 
MVVM In real life - Lea Cohen Tannoudji, Lightricks
MVVM In real life - Lea Cohen Tannoudji, LightricksMVVM In real life - Lea Cohen Tannoudji, Lightricks
MVVM In real life - Lea Cohen Tannoudji, Lightricks
 
Best Practices for Using Mobile SDKs - Lilach Wagner, SafeDK (AppLovin)
Best Practices for Using Mobile SDKs - Lilach Wagner, SafeDK (AppLovin)Best Practices for Using Mobile SDKs - Lilach Wagner, SafeDK (AppLovin)
Best Practices for Using Mobile SDKs - Lilach Wagner, SafeDK (AppLovin)
 
Building Apps with Flutter - Hillel Coren, Invoice Ninja
Building Apps with Flutter - Hillel Coren, Invoice NinjaBuilding Apps with Flutter - Hillel Coren, Invoice Ninja
Building Apps with Flutter - Hillel Coren, Invoice Ninja
 
New Android Project: The Most Important Decisions - Vasiliy Zukanov
New Android Project: The Most Important Decisions - Vasiliy ZukanovNew Android Project: The Most Important Decisions - Vasiliy Zukanov
New Android Project: The Most Important Decisions - Vasiliy Zukanov
 
Designing a Design System - Shai Mishali, Gett
Designing a Design System - Shai Mishali, GettDesigning a Design System - Shai Mishali, Gett
Designing a Design System - Shai Mishali, Gett
 
The Mighty Power of the Accessibility Service - Guy Griv, Pepper
The Mighty Power of the Accessibility Service - Guy Griv, PepperThe Mighty Power of the Accessibility Service - Guy Griv, Pepper
The Mighty Power of the Accessibility Service - Guy Griv, Pepper
 
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDevKotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
 
Flutter State Management - Moti Bartov, Tikal
Flutter State Management - Moti Bartov, TikalFlutter State Management - Moti Bartov, Tikal
Flutter State Management - Moti Bartov, Tikal
 
Reactive UI in android - Gil Goldzweig Goldbaum, 10bis
Reactive UI in android - Gil Goldzweig Goldbaum, 10bisReactive UI in android - Gil Goldzweig Goldbaum, 10bis
Reactive UI in android - Gil Goldzweig Goldbaum, 10bis
 
Fun with flutter animations - Divyanshu Bhargava, GoHighLevel
Fun with flutter animations - Divyanshu Bhargava, GoHighLevelFun with flutter animations - Divyanshu Bhargava, GoHighLevel
Fun with flutter animations - Divyanshu Bhargava, GoHighLevel
 
DroidconTLV 2019
DroidconTLV 2019DroidconTLV 2019
DroidconTLV 2019
 
Ok google, it's time to bot! - Hadar Franco, Albert + Stav Levi, Monday
Ok google, it's time to bot! - Hadar Franco, Albert + Stav Levi, MondayOk google, it's time to bot! - Hadar Franco, Albert + Stav Levi, Monday
Ok google, it's time to bot! - Hadar Franco, Albert + Stav Levi, Monday
 
Introduction to React Native - Lev Vidrak, Wix
Introduction to React Native - Lev Vidrak, WixIntroduction to React Native - Lev Vidrak, Wix
Introduction to React Native - Lev Vidrak, Wix
 
Bang-Bang, you have been hacked - Yonatan Levin, KolGene
Bang-Bang, you have been hacked - Yonatan Levin, KolGeneBang-Bang, you have been hacked - Yonatan Levin, KolGene
Bang-Bang, you have been hacked - Yonatan Levin, KolGene
 
Educating your app – adding ML edge to your apps - Maoz Tamir
Educating your app – adding ML edge to your apps - Maoz TamirEducating your app – adding ML edge to your apps - Maoz Tamir
Educating your app – adding ML edge to your apps - Maoz Tamir
 

Recently uploaded

Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 

Recently uploaded (20)

Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 

Intro to Dependency Injection - Or bar

  • 1. Intro To Dependency Injection Or Bar
  • 2. - What is a Dependency? - Dependency Injection - Dependency Inversion Principle - Dependency Injection Frameworks Agenda
  • 4. public class Example {
 DatabaseHelper mDatabaseHelper;
 
 public Example() {
 mDatabaseHelper = new DatabaseHelper();
 }
 
 public void doStuff() {
 ...
 mDatabaseHelper.loadUsers();
 ...
 }
 }
  • 5. - Dependency injection is a software design pattern that implements inversion of control for resolving dependencies - An injection is the passing of a dependency to a dependent object to use
  • 6. public class Example {
 DatabaseHelper mDatabaseHelper;
 
 public Example() {
 mDatabaseHelper = new DatabaseHelper();
 }
 }
  • 7. public class Example {
 DatabaseHelper mDatabaseHelper;
 
 public Example() {
 mDatabaseHelper = new DatabaseHelper();
 }
 } public class Example { 
 DatabaseHelper mDatabaseHelper;
 
 public Example(DatabaseHelper databaseHelper) {
 mDatabaseHelper = databaseHelper;
 }
 }
  • 8. public class Example {
 DatabaseHelper mDatabaseHelper;
 
 public Example() {
 mDatabaseHelper = new DatabaseHelper();
 }
 } public class Example {
 DatabaseHelper mDatabaseHelper; public Example() {
 mDatabaseHelper = new DatabaseHelper();
 }
 }
 public class Example { 
 DatabaseHelper mDatabaseHelper;
 
 public Example(DatabaseHelper databaseHelper) {
 mDatabaseHelper = databaseHelper;
 }
 } public class Example {
 DatabaseHelper mDatabaseHelper; 
 public Example(DatabaseHelper databaseHelper) {
 mDatabaseHelper = databaseHelper;
 }
 }

  • 9. public class Example {
 DatabaseHelper mDatabaseHelper;
 
 public Example() {
 }
 
 public void setDatabaseHelper(DatabaseHelper databaseHelper) {
 mDatabaseHelper = databaseHelper;
 }
 }
  • 10. - Shared dependencies - Configure dependencies externally - Separation of modules - Inherent testability Why?
  • 11. public class ExampleTest {
 @Mock DatabaseHelper mockDatabaseHelper;
 
 @Test
 public void testExample_doStuff() {
 Example example = new Example(mockDatabaseHelper);
 example.doStuff();
 mockDatabaseHelper.AssertGetDataWasCalled();
 }
 } public class Example { 
 DatabaseHelper mDatabaseHelper;
 
 public Example(DatabaseHelper databaseHelper) {
 mDatabaseHelper = databaseHelper;
 } public void doStuff() {
 ...
 mDatabaseHelper.loadUsers();
 ...
 }
 }
  • 12. - High-level modules should not depend on low-level modules. Both should depend on abstractions. - Abstractions should not depend on details. Details should depend on abstractions. Dependency Inversion Principle
  • 14. A is coupled to B
  • 15. - Bare bones ebook reader - Supports PDF files - Prints book contents to screen Ebook Reader
  • 17. public class CoolEBookReader {
 public void loadPage(String bookUri, int PageNumber) {
 String pdfContent = getPdfContent(bookUri, PageNumber);
 displayPage(pdfContent);
 } }
  • 18. public class CoolEBookReader {
 enum BookType {
 PDF,
 EPUB
 }
 
 public void loadPage(BookType bookType, String bookUri, int PageNumber) {
 String pageContent;
 if (bookType == BookType.PDF) {
 pageContent = getPdfContent(bookUri, PageNumber);
 } else if (bookType == BookType.EPUB) {
 pageContent = getEpubContent(bookUri, PageNumber);
 } else {
 throw new IllegalArgumentException("Unknown book type");
 }
 displayPage(pageContent); 
 }
 }
  • 19. public class CoolEBookReader {
 enum BookType {
 PDF,
 EPUB
 
 }
 
 enum PrinterType {
 SCREEN,
 VOICE
 
 }
 
 public void loadPage(BookType bookType, PrinterType printerType, String bookUri, int PageNumber) {
 String pageContent;
 if (bookType == BookType.PDF) {
 pageContent = getPdfContent(bookUri, PageNumber);
 } else if (bookType == BookType.EPUB) {
 pageContent = getEpubContent(bookUri, PageNumber);
 } else {
 throw new IllegalArgumentException("Unknown book type");
 }
 
 if (printerType == PrinterType.SCREEN) {
 displayPage(pageContent);
 } else if (printerType == PrinterType.VOICE) {
 readAloudPage(pageContent);
 } else {
 throw new IllegalArgumentException("Unknown printer type");
 }
 }
 }
  • 20. - High-level modules should not depend on low-level modules. Both should depend on abstractions. - Abstractions should not depend on details. Details should depend on abstractions. Dependency Inversion
  • 22. interface Reader {
 String read(String bookUri, int pagNumber); }
 
 interface Printer {
 void print(String pageContent);
 } public class CoolEBookReader {
 public void loadPage(Reader reader, Printer printer, String bookUri, int pageNumber) {
 String pageContent = reader.read(bookUri, pageNumber);
 printer.print(pageContent);
 }
 }
  • 23. interface Reader {
 String read(String bookUri, int pagNumber); }
 
 interface Printer {
 void print(String pageContent);
 } public class CoolEBookReader {
 public void loadPage(Reader reader, Printer printer, String bookUri, int pageNumber) {
 String pageContent = reader.read(bookUri, pageNumber);
 printer.print(pageContent);
 }
 } public class CoolEBookReader {
 public void loadPage(String bookUri, int PageNumber) {
 String pdfContent = getPdfContent(bookUri, PageNumber);
 displayPage(pdfContent);
 } }
  • 24. public class CoolEBookReaderTest {
 @Mock
 Reader mockReader;
 
 @Mock
 CoolEBookReader.Printer mockPrinter;
 
 @Test 
 public void TestExample_loadPage() {
 CoolEBookReader coolEBookReader = new CoolEBookReader();
 coolEBookReader.loadPage(mockReader, mockPrinter, "", 1);
 // Assert Reader.read() is called
 // Assert Printer.print() is called
 }
 }
  • 25. - Dependency Injection - Dependency Inversion - Where are these dependencies come from What’s next?
  • 26. - Handles object creation - Reduces boilerplate code - A central location for organizing dependencies - Implement common patterns natively (singleton, lazy loading, etc) Why use a framework?
  • 27. - Dagger 1 - Dagger 2 - Guice and RoboGuice - PicoContainer - Spring - Many, many, many, many more options Common Frameworks
  • 28. History lesson of DI on Android - RoboGuice - 2009 - Spring for Android - 2012 - Dagger 1 - 2013 - Dagger 2 - 2015 - Tiger - 2016
  • 29. - @javax.inject.Inject - @Module - @Provides - @Component Dagger uses annotations
  • 30. public class ConnectionHelper {
 private Context mContext;
 
 public ConnectionHelper(Context context) {
 mContext = context;
 }
 
 public boolean isConnected() {
 ConnectivityManager connectivityManager =
 (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
 return connectivityManager.getActiveNetworkInfo().isConnected();
 }
 } ConnectionHelper connectionHelper = new ConnectionHelper(context);
 
 boolean isConnected = connectionHelper.isConnected();
  • 31. public class ConnectionHelper {
 private Context mContext;
 
 @Inject
 public ConnectionHelper(Context context) {
 mContext = context;
 }
 
 public boolean isConnected() {
 ConnectivityManager connectivityManager =
 (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
 
 return connectivityManager.getActiveNetworkInfo().isConnected();
 }
 } @Inject
  • 32. @Module
 public class AppModule {
 
 } @Module
  • 33. @Provides @Module
 public class AppModule {
 private final Context mContext;
 
 public AppModule(Context context) {
 mContext = context;
 } @Provides
 public Context providesContext() {
 return mContext;
 } @Provides
 public ConnectionHelper providesConnectionHelper(Context context) {
 return new ConnectionHelper(context);
 }
 }
  • 34. @Component(modules = {AppModule.class})
 public interface AppComponent {
 
 void inject(MainActivity activity);
 } @Component
  • 35. public class App extends Application {
 private AppComponent component;
 @Override
 public void onCreate() {
 super.onCreate();
 
 AppComponent component = DaggerAppComponent.builder()
 .appModule(new AppModule(this))
 .build();
 }
 
 public AppComponent getComponent() {
 return component;
 }
 } public class App extends Application {
 private AppComponent component;
 @Override
 public void onCreate() {
 super.onCreate();
 
 AppComponent component = DaggerAppComponent.builder()
 .appModule(new AppModule(this))
 .build();
 }
 
 public AppComponent getComponent() {
 return component;
 }
 }
  • 36. public class MainActivity extends AppCompatActivity {
 
 @Inject
 ConnectionHelper mConnectionHelper;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 ((App) getApplication()).getComponent().inject(this);
 
 boolean isConnected = mConnectionHelper.isConnected();
 
 textView.setText(isConnected ? "Connected" : "Not Connected");
 }
 } public class MainActivity extends AppCompatActivity {
 
 @Inject
 ConnectionHelper mConnectionHelper;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 ((App) getApplication()).getComponent().inject(this);
 
 boolean isConnected = mConnectionHelper.isConnected();
 
 textView.setText(isConnected ? "Connected" : "Not Connected");
 }
 } @Inject - again
  • 37. - More annotations - Scopes - Lazy injections - others Fun stuff
  • 38. @Provides
 @Singleton
 public Context providesContext() {
 return context;
 } @Singleton @Singleton
 @Component(modules = {AppModule.class})
 public interface AppComponent {
 
 void inject(MainActivity activity); }
  • 39. @Provides
 @Reusable
 public ConnectionHelper providesConnectionHelper(Context context) {
 return new ConnectionHelper(context);
 } @Reusable @Singleton @Reusable
 @Component(modules = {AppModule.class})
 public interface AppComponent {}
  • 40. @Inject
 Lazy<ConnectionHelper> mConnectionHelper;
 ... mConnectionHelper.get().isConnected(); Lazy and Provider Injections @Inject
 Provider<ConnectionHelper> mConnectionHelper;
 ... mConnectionHelper.get().isConnected();
  • 41. @Target(ANNOTATION_TYPE)
 @Retention(RUNTIME)
 @Documented
 public @interface Qualifier {} @Qualifier @Qualifier
 @Documented
 @Retention(RUNTIME)
 public @interface Named {}
  • 42. @Provides @Singleton @Named(“Adapter 1”)
 public RestAdapter providesRestAdapter1() { return …; } @Qualifier @Provides @Singleton @Named(“Adapter 2”) public RestAdapter providesRestAdapter2() { return …; }
  • 44. Subcomponents and Scopes - Subcomponents allow you to combine different modules at runtime - Scopes let you define the lifetime of a dependency
  • 45. Testing and dagger - Constructors used for injections can be used for testing - Test Modules for espresso