SlideShare a Scribd company logo
1 of 37
Dependency Injection
Aman Verma
Why are we doing this ??
● To learn a new buzz word ??
● To improve code quality ??
● Is this all ??
Problem
We have a simple problem which we need to solve
Let say we have a class, Person, and this class needs
to send a message (Say email).
The Person class requires the aid of some other
class, Email, in order to send a message.
Is this ok ??
For a new Type of Email
For a new param addition to constructor
We have to change every instantiation of Email class
If we change Email to Singleton
For a new Message Delivery System
Design won’t scale with new Message Delivery
systems addition and we will have to make changes
everywhere
Testing
Here we cannot provide a stub
implementation since the class
instantiates the class
TDD is not possible
Case Study
Standard n-tier architecture
Mantra
Inversion of Control
● Invert the controls to achieve loose coupling
● The control means any additional responsibilities a class has other than its main responsibility,
such as control over the flow of an application, control over the flow of an object creation or
dependent object creation and binding. (Don't forget SRP)
● Analogy of Car
● If you want to do TDD then you must use IoC principle without which TDD is not possible.
Don't call us, we'll call you
● Software frameworks, callbacks, schedulers, event loops, dependency injection are examples of
design patterns that follow the inversion of control principle
● Helps in
○ To focus a module on the task it is designed for.
○ To free modules from assumptions about how other systems do what they do and
instead rely on contracts.
○ To prevent side effects when replacing a module.
What’s the issue ?
● Using Factory to achieve Ioc
● Is it ok now ??
Dependency Inversion Principle
● Dependency inversion principle refers to a specific form of decoupling software modules.
● High-level modules should not depend on low-level modules. Both should depend on
abstraction.
● Abstractions should not depend on details. Details should depend on abstractions.
Dependency Inversion Principle
CustomerBusinessLogic and CustomerDataAccess classes
are loosely coupled classes because
CustomerBusinessLogic does not depend on concrete
DataAccess class, instead it includes reference of
ICustomerDataAccess interface. So now, we can easily
use another class which implements
ICustomerDataAccess with different implementation.
Won’t this be awesome ?
● The problem with the solution is that we used DataAccessFactory inside
CustomerBusinessLogic class. So, suppose there is another implementation of
ICustomerDataAccess for some reason and we want to use that new class inside
CustomerBusinessLogic. Then, we need to change the source code of CustomerBusinessLogic
class also. (Violation of Open Closed Principle)
● All the dependencies must be provided externally.
● Can be done via factories
● Can be done via IoC Containers say Google Guice.
Dependency Injection
Google Guice to the rescue
● Guice’s job is to assemble graphs of objects. You request an instance of a given type, and it
figures out what to build, resolves dependencies, and wires everything together.
● Guice alleviates the need for factories and the use of new in your Java code. Think of Guice's
@Inject as the new new.
● Code will be easier to change, unit test and reuse in other contexts.
Guice Bindings - Linked Binding
● Linked bindings map a type to its implementation.
● This example maps the interface TransactionLog to the implementation
DatabaseTransactionLog
● Chaining of Bindings can also be done.
● In this case, when a TransactionLog is requested, the injector will return a
MySqlDatabaseTransactionLog.
Binding Annotations
● What if you want to bind different implementations of interfaces in different contexts ??
● For example, you might want both a PayPal credit card processor and a Google Checkout
processor to be bound to CreditCardProcessor Interface ?
Would I have to create annotations ?
Instance Binding
You can bind a type to a specific instance of that type. This is usually only useful only for objects that
don't have dependencies of their own, such as value objects:
Provides Binding
● When you need code to create an object, use an @Provides method.
● The method must be defined within a module, and it must have an @Provides annotation.
● Whenever the injector needs an instance of that type, it will invoke the method.
● Guice does not allow exceptions to be thrown from Providers. Exceptions thrown by @Provides
methods will be wrapped in a ProvisionException. It is bad practice to allow any kind of
exception to be thrown -- runtime or checked -- from an @Provides method.
Untargeted Bindings
● You may create bindings without specifying a target. This is most useful for concrete classes
● When specifying binding annotations, you must still add the target binding, even it is the same
concrete class
Just In Time Binding
● The bindings in a modules are called explicit bindings, and the injector uses them whenever
they're available.
● If a type is needed but there isn't an explicit binding, the injector will attempt to create a Just-In-
Time binding.
@ImplementedBy
● Annotate types tell the injector what their default implementation type is.
● The @ImplementedBy annotation acts like a linked binding, specifying the subtype to use when
building a type.
Questions ???

More Related Content

What's hot

What's hot (20)

Gerrit Code Review with GitHub plugin
Gerrit Code Review with GitHub pluginGerrit Code Review with GitHub plugin
Gerrit Code Review with GitHub plugin
 
Intro to vue.js
Intro to vue.jsIntro to vue.js
Intro to vue.js
 
Speeding up your team with GitOps
Speeding up your team with GitOpsSpeeding up your team with GitOps
Speeding up your team with GitOps
 
The journey to GitOps
The journey to GitOpsThe journey to GitOps
The journey to GitOps
 
Distributed fun with etcd
Distributed fun with etcdDistributed fun with etcd
Distributed fun with etcd
 
Containers: The What, Why, and How
Containers: The What, Why, and HowContainers: The What, Why, and How
Containers: The What, Why, and How
 
Grails Simple Login
Grails Simple LoginGrails Simple Login
Grails Simple Login
 
Rancher presentation august 2017
Rancher presentation august 2017Rancher presentation august 2017
Rancher presentation august 2017
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
 
Introduction to GitHub Actions
Introduction to GitHub ActionsIntroduction to GitHub Actions
Introduction to GitHub Actions
 
Kubernetes in Docker
Kubernetes in DockerKubernetes in Docker
Kubernetes in Docker
 
Docker swarm
Docker swarmDocker swarm
Docker swarm
 
Building Grails applications with PostgreSQL
Building Grails applications with PostgreSQLBuilding Grails applications with PostgreSQL
Building Grails applications with PostgreSQL
 
Grokking opensource with github
Grokking opensource with githubGrokking opensource with github
Grokking opensource with github
 
Why Vue.js?
Why Vue.js?Why Vue.js?
Why Vue.js?
 
GitHub Actions with Node.js
GitHub Actions with Node.jsGitHub Actions with Node.js
GitHub Actions with Node.js
 
Kubernetes 101
Kubernetes 101Kubernetes 101
Kubernetes 101
 
CI/CD with GitHub Actions
CI/CD with GitHub ActionsCI/CD with GitHub Actions
CI/CD with GitHub Actions
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 

Similar to Dependency Injection Simplifies Code

From Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developerFrom Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developerKaterina Trajchevska
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesWalking Tree Technologies
 
Boston Startup School - OO Design
Boston Startup School - OO DesignBoston Startup School - OO Design
Boston Startup School - OO DesignBryan Warner
 
Unit testing (Exploring the other side as a tester)
Unit testing (Exploring the other side as a tester)Unit testing (Exploring the other side as a tester)
Unit testing (Exploring the other side as a tester)Abhijeet Vaikar
 
Object Oriented, Design patterns and data modelling worshop
Object Oriented, Design patterns and data modelling worshopObject Oriented, Design patterns and data modelling worshop
Object Oriented, Design patterns and data modelling worshopMohammad Shawahneh
 
[Android] DI in multimodule application
[Android] DI in multimodule application[Android] DI in multimodule application
[Android] DI in multimodule applicationOleg Mazhukin
 
Android Dagger 2
Android  Dagger 2Android  Dagger 2
Android Dagger 2Sanket Shah
 
Design Patterns Part1
Design Patterns  Part1Design Patterns  Part1
Design Patterns Part1Tom Chen
 
Write testable code in java, best practices
Write testable code in java, best practicesWrite testable code in java, best practices
Write testable code in java, best practicesMarian Wamsiedel
 
Django Patterns - Pycon India 2014
Django Patterns - Pycon India 2014Django Patterns - Pycon India 2014
Django Patterns - Pycon India 2014arunvr
 
SOLID Design Principles for Test Automaion
SOLID Design Principles for Test AutomaionSOLID Design Principles for Test Automaion
SOLID Design Principles for Test AutomaionKnoldus Inc.
 
Create first android app with MVVM Architecture
Create first android app with MVVM ArchitectureCreate first android app with MVVM Architecture
Create first android app with MVVM Architecturekhushbu thakker
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2Knoldus Inc.
 
Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)Knoldus Inc.
 
Grasp oose week 14.pdf
Grasp oose week 14.pdfGrasp oose week 14.pdf
Grasp oose week 14.pdfNaveedChughtai
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@Alex Borsuk
 

Similar to Dependency Injection Simplifies Code (20)

From Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developerFrom Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developer
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
 
Boston Startup School - OO Design
Boston Startup School - OO DesignBoston Startup School - OO Design
Boston Startup School - OO Design
 
Unit testing (Exploring the other side as a tester)
Unit testing (Exploring the other side as a tester)Unit testing (Exploring the other side as a tester)
Unit testing (Exploring the other side as a tester)
 
Object Oriented, Design patterns and data modelling worshop
Object Oriented, Design patterns and data modelling worshopObject Oriented, Design patterns and data modelling worshop
Object Oriented, Design patterns and data modelling worshop
 
[Android] DI in multimodule application
[Android] DI in multimodule application[Android] DI in multimodule application
[Android] DI in multimodule application
 
Android Dagger 2
Android  Dagger 2Android  Dagger 2
Android Dagger 2
 
Design Patterns Part1
Design Patterns  Part1Design Patterns  Part1
Design Patterns Part1
 
Write testable code in java, best practices
Write testable code in java, best practicesWrite testable code in java, best practices
Write testable code in java, best practices
 
Django Patterns - Pycon India 2014
Django Patterns - Pycon India 2014Django Patterns - Pycon India 2014
Django Patterns - Pycon India 2014
 
Dagger2 Intro
Dagger2 IntroDagger2 Intro
Dagger2 Intro
 
Software Design principales
Software Design principalesSoftware Design principales
Software Design principales
 
SOLID Design Principles for Test Automaion
SOLID Design Principles for Test AutomaionSOLID Design Principles for Test Automaion
SOLID Design Principles for Test Automaion
 
Create first android app with MVVM Architecture
Create first android app with MVVM ArchitectureCreate first android app with MVVM Architecture
Create first android app with MVVM Architecture
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2
 
Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)
 
Grasp oose week 14.pdf
Grasp oose week 14.pdfGrasp oose week 14.pdf
Grasp oose week 14.pdf
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Spring Test Framework
Spring Test FrameworkSpring Test Framework
Spring Test Framework
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 

Recently uploaded

Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 

Recently uploaded (20)

Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 

Dependency Injection Simplifies Code

  • 2. Why are we doing this ?? ● To learn a new buzz word ?? ● To improve code quality ?? ● Is this all ??
  • 3.
  • 4. Problem We have a simple problem which we need to solve Let say we have a class, Person, and this class needs to send a message (Say email). The Person class requires the aid of some other class, Email, in order to send a message.
  • 6. For a new Type of Email
  • 7. For a new param addition to constructor We have to change every instantiation of Email class
  • 8. If we change Email to Singleton
  • 9. For a new Message Delivery System Design won’t scale with new Message Delivery systems addition and we will have to make changes everywhere
  • 10. Testing Here we cannot provide a stub implementation since the class instantiates the class TDD is not possible
  • 12.
  • 14. Inversion of Control ● Invert the controls to achieve loose coupling ● The control means any additional responsibilities a class has other than its main responsibility, such as control over the flow of an application, control over the flow of an object creation or dependent object creation and binding. (Don't forget SRP) ● Analogy of Car ● If you want to do TDD then you must use IoC principle without which TDD is not possible.
  • 15. Don't call us, we'll call you ● Software frameworks, callbacks, schedulers, event loops, dependency injection are examples of design patterns that follow the inversion of control principle ● Helps in ○ To focus a module on the task it is designed for. ○ To free modules from assumptions about how other systems do what they do and instead rely on contracts. ○ To prevent side effects when replacing a module.
  • 17. ● Using Factory to achieve Ioc ● Is it ok now ??
  • 18. Dependency Inversion Principle ● Dependency inversion principle refers to a specific form of decoupling software modules. ● High-level modules should not depend on low-level modules. Both should depend on abstraction. ● Abstractions should not depend on details. Details should depend on abstractions.
  • 20. CustomerBusinessLogic and CustomerDataAccess classes are loosely coupled classes because CustomerBusinessLogic does not depend on concrete DataAccess class, instead it includes reference of ICustomerDataAccess interface. So now, we can easily use another class which implements ICustomerDataAccess with different implementation.
  • 21.
  • 22. Won’t this be awesome ?
  • 23.
  • 24. ● The problem with the solution is that we used DataAccessFactory inside CustomerBusinessLogic class. So, suppose there is another implementation of ICustomerDataAccess for some reason and we want to use that new class inside CustomerBusinessLogic. Then, we need to change the source code of CustomerBusinessLogic class also. (Violation of Open Closed Principle) ● All the dependencies must be provided externally. ● Can be done via factories ● Can be done via IoC Containers say Google Guice. Dependency Injection
  • 25.
  • 26. Google Guice to the rescue ● Guice’s job is to assemble graphs of objects. You request an instance of a given type, and it figures out what to build, resolves dependencies, and wires everything together. ● Guice alleviates the need for factories and the use of new in your Java code. Think of Guice's @Inject as the new new. ● Code will be easier to change, unit test and reuse in other contexts.
  • 27. Guice Bindings - Linked Binding ● Linked bindings map a type to its implementation. ● This example maps the interface TransactionLog to the implementation DatabaseTransactionLog
  • 28. ● Chaining of Bindings can also be done. ● In this case, when a TransactionLog is requested, the injector will return a MySqlDatabaseTransactionLog.
  • 29. Binding Annotations ● What if you want to bind different implementations of interfaces in different contexts ?? ● For example, you might want both a PayPal credit card processor and a Google Checkout processor to be bound to CreditCardProcessor Interface ?
  • 30.
  • 31. Would I have to create annotations ?
  • 32. Instance Binding You can bind a type to a specific instance of that type. This is usually only useful only for objects that don't have dependencies of their own, such as value objects:
  • 33. Provides Binding ● When you need code to create an object, use an @Provides method. ● The method must be defined within a module, and it must have an @Provides annotation. ● Whenever the injector needs an instance of that type, it will invoke the method. ● Guice does not allow exceptions to be thrown from Providers. Exceptions thrown by @Provides methods will be wrapped in a ProvisionException. It is bad practice to allow any kind of exception to be thrown -- runtime or checked -- from an @Provides method.
  • 34. Untargeted Bindings ● You may create bindings without specifying a target. This is most useful for concrete classes ● When specifying binding annotations, you must still add the target binding, even it is the same concrete class
  • 35. Just In Time Binding ● The bindings in a modules are called explicit bindings, and the injector uses them whenever they're available. ● If a type is needed but there isn't an explicit binding, the injector will attempt to create a Just-In- Time binding.
  • 36. @ImplementedBy ● Annotate types tell the injector what their default implementation type is. ● The @ImplementedBy annotation acts like a linked binding, specifying the subtype to use when building a type.