SlideShare ist ein Scribd-Unternehmen logo
1 von 30
1

Dependency Injection
Constantine Nosovsky
2 of 30

Agenda
Program units coupling
Why one should avoid tight coupling
Problems of coupling reduction
Coupling reduction example
Dependency injection (DI): definition, components, injection type
Inversion of control (IoC)
IoC + DI
Dependency: lifecycle, scope, resolution
Reference implementations
Benefits and disadvantages
3 of 30

Program units coupling
Coupling is a measure of the independence of components
Tight (high, strong)
Module A

Module B

Loose (low, weak)
Module A

Module B

None
Module A
Module B

Module C

Module D

Module C

Module D

Module C
Module D
4 of 30

Program units coupling: types
Content: A modifies B, B is completely dependent on A
(e. g. A overrides implementation of method in B)
Common: A and B share the same common data
(e. g. A and B share the same global variable)
Control: A passes parameters to control the flow of B
Stamp: A and B share the same Value-Object type
Data: Only data are passed between A and B
Message: Defined message types are sent between A and B
None: A and B do not interact in any way
5 of 30

Why one should avoid tight coupling
A change in one module forces
a ripple effect of changes
in other modules

A particular module is harder
to reuse and test,
because dependent modules
must be included
6 of 30

Warning
Do NOT try to reduce coupling between every pair of units
just for the sake of loyalty, if it doesn’t feel right
Level of coupling is a matter of design, it is neither good or bad

For example:
• Module A doesn’t make any sense without module B
• A and B work as a whole atomic unit
(e.g. pipeline processing)
• The application is made to work with an exact
third-party Service, API or Hardware
7 of 30

Coupling reduction
8 of 30

Problems of coupling reduction
Components independence: modules make no assumptions
about what other systems do, but rely on their contracts
Abstraction: use interface to define a type
and focus on what is important about the component
Instantiation: concrete implementation of the interface
has to be instantiated (creational patterns like Abstract Factory)

Components linking: provide a wiring layer
between components A and B (Service Locator)
9 of 30

Example: tight coupling
public class A {
B b = new B();
C c = new C();
public void doA() {
b.doB();
c.doC();
}
}
10 of 30

Example: abstraction (use interfaces)
public class A {
IB b = new B();
IC c = new C();
public void doA() {
b.doB();
c.doC();
}
}
11 of 30

Example: instantiation (creational
patterns)
public class A {
IB b = FactoryB.createIB();
IC c = FactoryC.createIC();
public void doA() {
b.doB();
c.doC();
}
}
12 of 30

Example: components linking
public class A {
IB b; IC c;
public A(IB b, IC c) {
this.b = b;
this.c = c;
}
public void doA() {
b.doB();
c.doC();
}
}
13 of 30

Example: components linking
public class Starter {
A a; IB b; IC c;
public void startUp() {
b = FactoryB.createIB();
c = FactoryC.createIC();
a = new A(b, c);
}
public A getA() {
return a;
}
}
14 of 30

Example: loose coupling
15 of 30

Dependency injection (DI)
So we noticed that decoupled modules
need to be linked for the interaction
16 of 30

DI: definition
Dependency Injection (DI) is a design pattern
aimed to eliminate the hard-coded dependencies
between program modules and make it possible
to change them at compile-time and/or run-time
17 of 30

DI: components
Dependency: a module that other modules depend on
Consumer (Client): a dependent module
Injector (Container): a component that retrieves/creates
dependencies and wires them to the consumers
Resolver: a component that chooses a concrete implementation
for the abstract type requested
18 of 30

DI: illustration
19 of 30

DI: injection types
Constructor: dependency is wired during the consumer is being
created
Setter: setter method is used to set/change the dependency
Interface: dependency provides an interface that must be
implemented by any dependent client
20 of 30

Inversion of control (IoC)
“Don’t call us, we’ll call you”
Methods defined by the user to tailor the framework will often be
called from within the framework itself
Framework plays the role of main application and user code
defines action to perform in response to application activity
21 of 30

IoC + DI
IoC framework
Application

DI Container

Configuration
Metadata

Modules

Application
Configuration

Localized texts,
etc.
22 of 30

IoC + DI: configuration metadata
External: XML or other external metadata format
<bean class="com.example.MyComponent"/>
Annotation-based: byte-code level metadata description
@Component
public class MyComponent { … }
Code-based: custom code that declares dependencies
@Configuration
public class AppConfig {
@Bean public MyComponent myComponent () {
return new MyComponent();
}
}
23 of 30

Dependency: lifecycle
Creation: dependencies may be created calling the default
constructor (default) or factory method

•
•
•
•
•

Callbacks: container provides a set of callbacks called on events:
Dependency initialization (pre and post)
Dependency destruction (pre and post)
Container startup
Container shutdown
etc.
24 of 30

Dependency: scopes
Singleton (container): a single instance for the whole container
Prototype: a single definition for any amount of instances
Thread: a single instance per thread (thread scope singleton)
Custom: define your own scope
Web aware containers may provide:
Request
Session
25 of 30

Dependency: resolution
Explicit reference wiring configuration
Autowiring
• Type: the dependency is resolved based on class type
• Name: based on unique component name
• Collections of types
26 of 30

Example: using DI
@Component
public class A {
IB b; IC c;
@Autowired
public A(IB b, IC c) {
this.b = b;
this.c = c;
}
}
27 of 30

Reference implementations
Java
• J2EE 6+ compatible containers (Glassfish, etc.)
• Spring – a part of the large versatile framework
• Google Guice – lightweight, works for android
.NET
• Spring.NET
28 of 30

Benefits
More readable code
More testable code
More reusable code
29 of 30

Disadvantages
Runtime linking cause runtime errors instead of compiletime
Longer application startup

•
•
•
•

Dependency hell:
Circular dependencies
Conflicting dependencies
Long chains of dependencies
A lot of dependencies for a simple functionality
30 of 30

Thanks for your attention

?

Weitere ähnliche Inhalte

Andere mochten auch

Intelligent well completion
Intelligent well completionIntelligent well completion
Intelligent well completionAkshaya Mishra
 
Going native with less coupling: Dependency Injection in C++
Going native with less coupling: Dependency Injection in C++Going native with less coupling: Dependency Injection in C++
Going native with less coupling: Dependency Injection in C++Daniele Pallastrelli
 
Well completion and stimulation
Well completion and stimulation Well completion and stimulation
Well completion and stimulation kaleem ullah
 
Petroleum production engineering
Petroleum production engineeringPetroleum production engineering
Petroleum production engineeringMaanik Gupta
 
Oil & Gas Production and Surface Facilities
Oil & Gas Production and Surface FacilitiesOil & Gas Production and Surface Facilities
Oil & Gas Production and Surface FacilitiesMohamed Elnagar
 

Andere mochten auch (7)

Intelligent well completion
Intelligent well completionIntelligent well completion
Intelligent well completion
 
Intelligent well completions
Intelligent well completionsIntelligent well completions
Intelligent well completions
 
Going native with less coupling: Dependency Injection in C++
Going native with less coupling: Dependency Injection in C++Going native with less coupling: Dependency Injection in C++
Going native with less coupling: Dependency Injection in C++
 
Well completion and stimulation
Well completion and stimulation Well completion and stimulation
Well completion and stimulation
 
EOR Methods
EOR MethodsEOR Methods
EOR Methods
 
Petroleum production engineering
Petroleum production engineeringPetroleum production engineering
Petroleum production engineering
 
Oil & Gas Production and Surface Facilities
Oil & Gas Production and Surface FacilitiesOil & Gas Production and Surface Facilities
Oil & Gas Production and Surface Facilities
 

Ähnlich wie Dependency Injection

FP 301 OOP FINAL PAPER JUNE 2013
FP 301 OOP FINAL PAPER JUNE 2013FP 301 OOP FINAL PAPER JUNE 2013
FP 301 OOP FINAL PAPER JUNE 2013Syahriha Ruslan
 
D1 from interfaces to solid
D1 from interfaces to solidD1 from interfaces to solid
D1 from interfaces to solidArnaud Bouchez
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NETssusere19c741
 
Unit3 Software engineering UPTU
Unit3 Software engineering UPTUUnit3 Software engineering UPTU
Unit3 Software engineering UPTUMohammad Faizan
 
FP 303 COMPUTER NETWORK FINAL PAPER JUNE 2012
FP 303 COMPUTER NETWORK FINAL PAPER JUNE 2012FP 303 COMPUTER NETWORK FINAL PAPER JUNE 2012
FP 303 COMPUTER NETWORK FINAL PAPER JUNE 2012Syahriha Ruslan
 
Software Engineering Unit 3 PPT Software Design
Software Engineering Unit 3 PPT Software DesignSoftware Engineering Unit 3 PPT Software Design
Software Engineering Unit 3 PPT Software Designmayanksingh678141
 
Introduction to Configurator 2.0 architecture design
Introduction to Configurator 2.0 architecture designIntroduction to Configurator 2.0 architecture design
Introduction to Configurator 2.0 architecture designXiaoyan Chen
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMING
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMINGFINAL PAPER FP301 OBJECT ORIENTED PROGRAMMING
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMINGAmira Dolce Farhana
 
C# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slidesC# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slidesSami Mut
 
Modeling an ODE: 3 different approaches - Part 3
Modeling an ODE: 3 different approaches - Part 3Modeling an ODE: 3 different approaches - Part 3
Modeling an ODE: 3 different approaches - Part 3Scilab
 
Software Architecture Taxonomies - modularity
Software Architecture Taxonomies - modularitySoftware Architecture Taxonomies - modularity
Software Architecture Taxonomies - modularityJose Emilio Labra Gayo
 
Session 3 Software Engineering UGC NET.pdf
Session 3 Software Engineering UGC NET.pdfSession 3 Software Engineering UGC NET.pdf
Session 3 Software Engineering UGC NET.pdfsangeethachandran
 
Which is not a step in the problem
Which is not a step in the problemWhich is not a step in the problem
Which is not a step in the problemkasguest
 
Which is not a step in the problem
Which is not a step in the problemWhich is not a step in the problem
Which is not a step in the problemkasguest
 
Vlsilab13
Vlsilab13Vlsilab13
Vlsilab13Krish s
 
Fogify: A Fog Computing Emulation Framework
Fogify: A Fog Computing Emulation FrameworkFogify: A Fog Computing Emulation Framework
Fogify: A Fog Computing Emulation FrameworkMoysisSymeonides
 

Ähnlich wie Dependency Injection (20)

FP 301 OOP FINAL PAPER JUNE 2013
FP 301 OOP FINAL PAPER JUNE 2013FP 301 OOP FINAL PAPER JUNE 2013
FP 301 OOP FINAL PAPER JUNE 2013
 
D1 from interfaces to solid
D1 from interfaces to solidD1 from interfaces to solid
D1 from interfaces to solid
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NET
 
Unit3 Software engineering UPTU
Unit3 Software engineering UPTUUnit3 Software engineering UPTU
Unit3 Software engineering UPTU
 
FP 303 COMPUTER NETWORK FINAL PAPER JUNE 2012
FP 303 COMPUTER NETWORK FINAL PAPER JUNE 2012FP 303 COMPUTER NETWORK FINAL PAPER JUNE 2012
FP 303 COMPUTER NETWORK FINAL PAPER JUNE 2012
 
Software Engineering Unit 3 PPT Software Design
Software Engineering Unit 3 PPT Software DesignSoftware Engineering Unit 3 PPT Software Design
Software Engineering Unit 3 PPT Software Design
 
SE UNIT-3.pdf
SE UNIT-3.pdfSE UNIT-3.pdf
SE UNIT-3.pdf
 
Introduction to Configurator 2.0 architecture design
Introduction to Configurator 2.0 architecture designIntroduction to Configurator 2.0 architecture design
Introduction to Configurator 2.0 architecture design
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMING
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMINGFINAL PAPER FP301 OBJECT ORIENTED PROGRAMMING
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMING
 
C# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slidesC# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slides
 
Visual programming
Visual programmingVisual programming
Visual programming
 
Modeling an ODE: 3 different approaches - Part 3
Modeling an ODE: 3 different approaches - Part 3Modeling an ODE: 3 different approaches - Part 3
Modeling an ODE: 3 different approaches - Part 3
 
Software Architecture Taxonomies - modularity
Software Architecture Taxonomies - modularitySoftware Architecture Taxonomies - modularity
Software Architecture Taxonomies - modularity
 
Session 3 Software Engineering UGC NET.pdf
Session 3 Software Engineering UGC NET.pdfSession 3 Software Engineering UGC NET.pdf
Session 3 Software Engineering UGC NET.pdf
 
Which is not a step in the problem
Which is not a step in the problemWhich is not a step in the problem
Which is not a step in the problem
 
Which is not a step in the problem
Which is not a step in the problemWhich is not a step in the problem
Which is not a step in the problem
 
COM Introduction
COM IntroductionCOM Introduction
COM Introduction
 
Vlsilab13
Vlsilab13Vlsilab13
Vlsilab13
 
Fogify: A Fog Computing Emulation Framework
Fogify: A Fog Computing Emulation FrameworkFogify: A Fog Computing Emulation Framework
Fogify: A Fog Computing Emulation Framework
 

Kürzlich hochgeladen

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Kürzlich hochgeladen (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

Dependency Injection

  • 2. 2 of 30 Agenda Program units coupling Why one should avoid tight coupling Problems of coupling reduction Coupling reduction example Dependency injection (DI): definition, components, injection type Inversion of control (IoC) IoC + DI Dependency: lifecycle, scope, resolution Reference implementations Benefits and disadvantages
  • 3. 3 of 30 Program units coupling Coupling is a measure of the independence of components Tight (high, strong) Module A Module B Loose (low, weak) Module A Module B None Module A Module B Module C Module D Module C Module D Module C Module D
  • 4. 4 of 30 Program units coupling: types Content: A modifies B, B is completely dependent on A (e. g. A overrides implementation of method in B) Common: A and B share the same common data (e. g. A and B share the same global variable) Control: A passes parameters to control the flow of B Stamp: A and B share the same Value-Object type Data: Only data are passed between A and B Message: Defined message types are sent between A and B None: A and B do not interact in any way
  • 5. 5 of 30 Why one should avoid tight coupling A change in one module forces a ripple effect of changes in other modules A particular module is harder to reuse and test, because dependent modules must be included
  • 6. 6 of 30 Warning Do NOT try to reduce coupling between every pair of units just for the sake of loyalty, if it doesn’t feel right Level of coupling is a matter of design, it is neither good or bad For example: • Module A doesn’t make any sense without module B • A and B work as a whole atomic unit (e.g. pipeline processing) • The application is made to work with an exact third-party Service, API or Hardware
  • 7. 7 of 30 Coupling reduction
  • 8. 8 of 30 Problems of coupling reduction Components independence: modules make no assumptions about what other systems do, but rely on their contracts Abstraction: use interface to define a type and focus on what is important about the component Instantiation: concrete implementation of the interface has to be instantiated (creational patterns like Abstract Factory) Components linking: provide a wiring layer between components A and B (Service Locator)
  • 9. 9 of 30 Example: tight coupling public class A { B b = new B(); C c = new C(); public void doA() { b.doB(); c.doC(); } }
  • 10. 10 of 30 Example: abstraction (use interfaces) public class A { IB b = new B(); IC c = new C(); public void doA() { b.doB(); c.doC(); } }
  • 11. 11 of 30 Example: instantiation (creational patterns) public class A { IB b = FactoryB.createIB(); IC c = FactoryC.createIC(); public void doA() { b.doB(); c.doC(); } }
  • 12. 12 of 30 Example: components linking public class A { IB b; IC c; public A(IB b, IC c) { this.b = b; this.c = c; } public void doA() { b.doB(); c.doC(); } }
  • 13. 13 of 30 Example: components linking public class Starter { A a; IB b; IC c; public void startUp() { b = FactoryB.createIB(); c = FactoryC.createIC(); a = new A(b, c); } public A getA() { return a; } }
  • 14. 14 of 30 Example: loose coupling
  • 15. 15 of 30 Dependency injection (DI) So we noticed that decoupled modules need to be linked for the interaction
  • 16. 16 of 30 DI: definition Dependency Injection (DI) is a design pattern aimed to eliminate the hard-coded dependencies between program modules and make it possible to change them at compile-time and/or run-time
  • 17. 17 of 30 DI: components Dependency: a module that other modules depend on Consumer (Client): a dependent module Injector (Container): a component that retrieves/creates dependencies and wires them to the consumers Resolver: a component that chooses a concrete implementation for the abstract type requested
  • 18. 18 of 30 DI: illustration
  • 19. 19 of 30 DI: injection types Constructor: dependency is wired during the consumer is being created Setter: setter method is used to set/change the dependency Interface: dependency provides an interface that must be implemented by any dependent client
  • 20. 20 of 30 Inversion of control (IoC) “Don’t call us, we’ll call you” Methods defined by the user to tailor the framework will often be called from within the framework itself Framework plays the role of main application and user code defines action to perform in response to application activity
  • 21. 21 of 30 IoC + DI IoC framework Application DI Container Configuration Metadata Modules Application Configuration Localized texts, etc.
  • 22. 22 of 30 IoC + DI: configuration metadata External: XML or other external metadata format <bean class="com.example.MyComponent"/> Annotation-based: byte-code level metadata description @Component public class MyComponent { … } Code-based: custom code that declares dependencies @Configuration public class AppConfig { @Bean public MyComponent myComponent () { return new MyComponent(); } }
  • 23. 23 of 30 Dependency: lifecycle Creation: dependencies may be created calling the default constructor (default) or factory method • • • • • Callbacks: container provides a set of callbacks called on events: Dependency initialization (pre and post) Dependency destruction (pre and post) Container startup Container shutdown etc.
  • 24. 24 of 30 Dependency: scopes Singleton (container): a single instance for the whole container Prototype: a single definition for any amount of instances Thread: a single instance per thread (thread scope singleton) Custom: define your own scope Web aware containers may provide: Request Session
  • 25. 25 of 30 Dependency: resolution Explicit reference wiring configuration Autowiring • Type: the dependency is resolved based on class type • Name: based on unique component name • Collections of types
  • 26. 26 of 30 Example: using DI @Component public class A { IB b; IC c; @Autowired public A(IB b, IC c) { this.b = b; this.c = c; } }
  • 27. 27 of 30 Reference implementations Java • J2EE 6+ compatible containers (Glassfish, etc.) • Spring – a part of the large versatile framework • Google Guice – lightweight, works for android .NET • Spring.NET
  • 28. 28 of 30 Benefits More readable code More testable code More reusable code
  • 29. 29 of 30 Disadvantages Runtime linking cause runtime errors instead of compiletime Longer application startup • • • • Dependency hell: Circular dependencies Conflicting dependencies Long chains of dependencies A lot of dependencies for a simple functionality
  • 30. 30 of 30 Thanks for your attention ?