SlideShare a Scribd company logo
1 of 59
www.italiancpp.org
Going native with less
coupling
Dependency Injection in C++
Italian C++ Community
Style 1: [Fake] OO Design
i=2
CONTROLLER /
MANAGER
Dumb
object
Dumb
object
Dumb
object
Dumb
object
Dumb
object
Dumb
object
Dumb
object
Dumb
object
Italian C++ Community
Style 2: [True] OO design
i=3
Smart
Object
Smart
Object
Smart
Object
Smart
Object
Smart
Object
Smart
Object
Smart
Object
Smart
Object
Smart
Object
Smart
Object
Smart
Object
Smart
Object
Smart
Object
Smart
Object
Italian C++ Community
OO Architecture Benefits
i=4
Up Scalability (extension)
Down Scalability
(contraction)
Reusability
Safety (testability)
Italian C++ Community i=5
The Wiring
Issue
In a True Modular Architecture, wiring is critical
Italian C++ Community
The Wiring Issue
When you've got a Good Architecture, you deal with
requirements changes by adding/removing/substituting objects
So, we need a simple way to:
Change the type of the objects
Create new objects
Modify the wiring of the objects
i=6
Italian C++ Community i=7
Life without a
CONTROLLER
Example taken from:
Carlo Pescio's blog – March 2012
Italian C++ Community
First Design
i=8
MinePlant
SumpPump
+Drain()
PumpEngine
+On()
+Off()
DigitalOutput
+Write()
GasSensor
<<interface>>
+IsCritical()
GasAlarm
+Watch()
1..*
Alarm
+On()
+Off()
SafeEngine
Italian C++ Community
Requirements Change
i=9
MinePlant
SumpPump
+Drain()
PumpEngine
+On()
+Off()
DigitalOutput
+Write()
GasSensor
<<interface>>
+IsCritical()
GasAlarm
+Watch()
1..*
Alarm
+On()
+Off()
SafeEngine
Italian C++ Community
Extension
The design is robust: I only need to add a class
But…
Who creates SafeEngine instead of PumpEngine?
How does SafeEngine get the pointer to the
GasSensor (the same used by GasAlarm)?
i=10
Italian C++ Community
Solution #1: Local Creation
Each class creates its own
dependencies
i=11
Italian C++ Community i=12
MinePlant
SumpPump
+Drain()
PumpEngine
+On()
+Off()
DigitalOutput
+Write()
GasSensor
<<interface>>
+IsCritical()
GasAlarm
+Watch()
1..*
Alarm
+On()
+Off()
SafeEngine <<create>>
Italian C++ Community
Solution #1: Consequences
The SumpPump constructor creates a SafeEngine
instead of a PumpEngine.
… but SafeEngine needs a pointer to the GasSensor
instance already used by GasAlarm.
So, we must pass it as a parameter to SumpPump
constructor.
i=13
Italian C++ Community
Solution #1: Properties
If I need to change the concrete
type, I have to modify the client.
It's difficult to reuse the same client
class (even in the same application).
i=14
Italian C++ Community
Solution #1: Summary
SafeEngine class added
SumpPump constructor modified
MinePlant modified
i=15
Italian C++ Community
Solution #2: Factory
(not the GoF factory)
Create objects without exposing
the instantiation logic to the client
i=16
Italian C++ Community i=17
<<create>>
Italian C++ Community
Solution #2: Consequences
The SumpPump constructor takes a Factory as
parameter.
PumpEngineFactory instantiates a PumpEngine.
SafeEngineFactory instantiates a SafeEngine.
SafeEngine still needs a pointer to the GasSensor
instance already used by GasAlarm, so we must pass
it to the SafeEngineFactory constructor.
i=18
Italian C++ Community
Solution #2: Summary
SafeEngine class added
SafeEngineFactory added
MinePlant modified
i=19
Italian C++ Community
Solution #3: Service Locator
It’s a registry containing the
instances to use
i=20
Italian C++ Community
Solution #3: Service Locator
i=21
class ServiceLocator
{
public:
static ServiceLocator& Instance();
shared_ptr< PumpEngine > Engine();
void Engine( const shared_ptr< PumpEngine >& engine );
private:
...
};
Italian C++ Community
Solution #3: Service Locator
i=22
// MinePlant:
auto e =
make_shared< SafeEngine >( engineOutput, gasSensor );
ServiceLocator::Instance().Engine( e );
// SumpPump:
SumpPump::SumpPump() :
engine( ServiceLocator::Instance().Engine() )
{
}
Italian C++ Community
Solution #3: Properties
Clients aware of the locator
Dependencies not explicit / evident
Dependencies not checked by compiler
i=23
Italian C++ Community
Solution #3: Summary
SafeEngine class added
MinePlant modified
i=24
Italian C++ Community
Solution #4: Dependency Injection
Dependency Injection is when
you have something setting the
dependencies for you.
i=25
Italian C++ Community
Solution #4: Dependency Injection
Classes don't create their own dependencies
They're passed from outside
i=26
Italian C++ Community
Dependency Injection
i=27
auto gasSensor = ...
auto alarmOutput = make_shared<DigitalOutput>("/dev/ttyS0");
auto alarm = make_shared<Alarm>(alarmOutput);
auto gasAlarm = make_shared<GasAlarm>(gasSensor,alarm);
auto engineOutput = make_shared<DigitalOutput>("/dev/ttyS1");
auto engine = make_shared<PumpEngine>(engineOutput);
auto pump = make_shared<SumpPump>(engine);
Italian C++ Community
Dependency Injection
i=28
auto gasSensor = ...
auto alarmOutput = make_shared<DigitalOutput>("/dev/ttyS0");
auto alarm = make_shared<Alarm>(alarmOutput);
auto gasAlarm = make_shared<GasAlarm>(gasSensor,alarm);
auto engineOutput = make_shared<DigitalOutput>("/dev/ttyS1");
// auto engine = make_shared<PumpEngine>(engineOutput);
auto engine = make_shared<SafeEngine>(engineOutput,gasSensor);
auto pump = make_shared<SumpPump>(engine);
Italian C++ Community
Solution #4: Properties
Complete separation between:
application logic (classes)
wiring (main/builder)
i=29
Italian C++ Community
Solution #4: Summary
SafeEngine class added
MinePlant modified (one liner)
i=30
Italian C++ Community i=31
Can we do
BETTER
SafeEngine must be added anyway.
… can we remove the one liner in MinePlant?
?
Italian C++ Community i=32
Configuration
DrivenWIRING
moving creation and wiring outside the code,
in a configuration file
Italian C++ Community
Why?
To easily get extensibility/contraction
(without having to touch zillion files and
recompile everything)
i=33
Italian C++ Community
From Identifiers to Strings
Improving Previous Solution:
Objects creation from string
Objects identified by name
Objects connected by name
i=34
Italian C++ Community
Run-time Reflection Missing…
Create("Foo") vs new Foo
Enumerate the dependencies
“Inject” the right object address in a
class dependency
i=35
Italian C++ Community
Solution #5: Dependency Injection +
Dependency Injection is when you
have something setting the
dependencies for you.
…this something is usually a
framework.
i=36
Italian C++ Community
Existing libraries (C++)
i=37
QtIOCContainer
Sauce
DICPP
Hypodermic2
Pococapsule
Main issues:
Compile time injection only
Code generators needed
Italian C++ Community
Enter Wallaroo Library
i=38
wallaroo.googlecode.com
wallarooC++ Dependency Injection
Italian C++ Community
Creating objects
i=39
Catalog catalog;
...
catalog.Create("alarmOutput","DigitalOutput","/dev/ttyS0");
catalog.Create("alarm","Alarm");
catalog.Create("gasAlarm","GasAlarm");
catalog.Create("engineOutput","DigitalOutput","/dev/ttyS1");
catalog.Create("pump","SumpPump");
catalog.Create("engine","SafeEngine");
Italian C++ Community
Creating objects (from cfg)
i=40
<parts>
<part>
<name>pump</name>
<class>SumpPump</class>
</part>
<part>
<name>engine</name>
<class>SafeEngine</class>
</part>
</parts>
...
Catalog catalog;
XmlConfiguration
file("wiring.xml");
file.Fill( catalog );
...
Italian C++ Community
Object lookup by name
i=41
shared_ptr< SumpPump > pump = catalog[ "pump" ];
Italian C++ Community
Connect Things by name (DSL)
i=42
Catalog catalog;
// fill catalog
...
use(catalog["alarmOutput"]).as("out").of(catalog["alarm" ]);
use(catalog["safeEngine"]).as("engine").of(catalog["pump"]);
Italian C++ Community
Connect Things by name (DSL)
i=43
Catalog catalog;
// fill catalog
...
wallaroo_within( catalog )
{
use( "alarmOutput" ).as( "out" ).of( "alarm" );
use( "safeEngine" ).as( "engine" ).of( "pump" );
}
Italian C++ Community
Connect Things by name (from cfg)
i=44
<wiring>
<wire>
<source>alarm</source>
<dest>alarmOutput</dest>
<collaborator>out</collaborator>
</wire>
<wire>
<source>pump</source>
<dest>safeEngine</dest>
<collaborator>engine</collaborator>
</wire>
</wiring>
Catalog catalog;
...
XmlConfiguration
file( "wiring.xml" );
file.Fill( catalog );
catalog.CheckWiring();
...
Italian C++ Community
Class Declaration
i=45
#include "wallaroo/registered.h"
using namespace wallaroo;
class SumpPump : public Part
{
public:
SumpPump( int id );
private:
Collaborator< Engine > engine;
};
Italian C++ Community
Class Registration
i=46
WALLAROO_REGISTER( SumpPump, int )
SumpPump::SumpPump( int id ) :
engine( "engine", RegistrationToken() )
{
...
}
// other methods definition here
...
Italian C++ Community
Shared Libraries – AKA plugins (code)
i=47
Plugin::Load( "safeengine" + Plugin::Suffix() );
// Plugin::Suffix() expands to .dll or .so according
to the OS
Italian C++ Community
Shared Libraries – AKA plugins (cfg)
i=48
<plugins>
<shared>safeengine</shared>
</plugins>
Catalog catalog;
XmlConfiguration file( "wiring.xml" );
// load the shared libraries specified in the configuration file:
file.LoadPlugins();
file.Fill( catalog );
// throws a WiringError exception if any dependency is missing:
catalog.CheckWiring();
Italian C++ Community
Collections
i=49
class Car : public wallaroo::Part
{
...
private:
Collaborator< Engine > engine;
Collaborator< AirConditioning, optional > airConditioning;
Collaborator< Airbag, collection > airbags;
Collaborator< Speaker, collection, std::list > speakers;
Collaborator< Seat, bounded_collection< 2, 6 > > seats;
};
Italian C++ Community
Checks
i=50
if ( !catalog.IsWiringOk() )
{
// error handling
}
catalog.CheckWiring() // throws exception
Italian C++ Community
Initialization
i=51
class Part
{
...
public:
virtual void Init() {}
...
};
catalog.Init() // calls Part::Init for each part in catalog
Italian C++ Community
Wallaroo Internals
WALLAROO_REGISTER declares a static object.
Its constructor creates a factory and puts it in a table, with the class
name as key.
Catalog::Create uses the factory to put a new instance in the catalog.
wallaroo::Part has a table of <name, Collaborator>
i=52
Italian C++ Community
Wallaroo Internals
shared_ptr< Foo > foo = catalog[ “foo” ];
catalog[ “foo” ] returns a class that defines operator
shared_ptr< T >()
Collaborator uses weak_ptr for the dependency
Collaborator defines operator shared_ptr() and operator->()
i=53
Italian C++ Community
Wallaroo Internals
i=54
wallaroo_within( catalog )
{
use("alarmOutput").as("out").of("alarm");
use("safeEngine").as("engine").of("pump");
}
for ( Context c(catalog);c.FirstTime();c.Terminate() )
{
use("alarmOutput").as("out").of("alarm");
use("safeEngine").as("engine").of("pump");
}
Italian C++ Community
Wallaroo Strengths
Lightweight (header file only)
Portable
Type Safe
DSL syntax for object creation and wiring
Configuration driven wiring (xml and json)
Shared library support (plugin)
C++11/14 or boost interface
No code generators
i=55
Italian C++ Community
Design is a balance of forces
Intrusive VS Non Intrusive
Non Intrusive Solutions can manage existing classes but
require code generators for configuration driven wiring
i=56
Italian C++ Community
Design is a balance of forces
Configuration-driven wiring
VS static type checking
By moving the wiring in a configuration file, we give up the
static type checking.
But it’s ok, since you build your system at startup.
i=57
Italian C++ Community
Action Points
Real OOD (no controllers / managers)
Manual Dependency Injection
Wallaroo (configuration-driven wiring)
i=58
Italian C++ Community
References & Credits
Me: @DPallastrelli
Me: it.linkedin.com/in/pallad
Rate me: https://joind.in/12277
Wallaroo: wallaroo.googlecode.com
i=59
MinePlant example from Carlo Pescio's blog (http://www.carlopescio.com/2012/03/life-
without-controller-case-1.html)
Wiring Picture: By Gael Mace (Own work (Personal photograph))
[CC-BY-3.0 (http://creativecommons.org/licenses/by/3.0)], via Wikimedia Commons

More Related Content

What's hot

CSW2017 Qinghao tang+Xinlei ying vmware_escape_final
CSW2017 Qinghao tang+Xinlei ying vmware_escape_finalCSW2017 Qinghao tang+Xinlei ying vmware_escape_final
CSW2017 Qinghao tang+Xinlei ying vmware_escape_finalCanSecWest
 
NDC15 - 사례로 살펴보는 MSVC 빌드 최적화 팁
NDC15 - 사례로 살펴보는 MSVC 빌드 최적화 팁NDC15 - 사례로 살펴보는 MSVC 빌드 최적화 팁
NDC15 - 사례로 살펴보는 MSVC 빌드 최적화 팁Yi-kwon Hwang
 
TaaS: Testbeds como Serviço
TaaS: Testbeds como ServiçoTaaS: Testbeds como Serviço
TaaS: Testbeds como ServiçoLeandro Ciuffo
 
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기Chris Ohk
 
[오픈소스컨설팅]오픈소스메일시스템
[오픈소스컨설팅]오픈소스메일시스템[오픈소스컨설팅]오픈소스메일시스템
[오픈소스컨설팅]오픈소스메일시스템Ji-Woong Choi
 
쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기Brian Hong
 
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015PostgreSQL-Consulting
 
청강대 특강 - 프로젝트 제대로 해보기
청강대 특강 - 프로젝트 제대로 해보기청강대 특강 - 프로젝트 제대로 해보기
청강대 특강 - 프로젝트 제대로 해보기Chris Ohk
 
[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정
[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정
[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정PgDay.Seoul
 
Spring Boot Actuator 2.0 & Micrometer
Spring Boot Actuator 2.0 & MicrometerSpring Boot Actuator 2.0 & Micrometer
Spring Boot Actuator 2.0 & MicrometerToshiaki Maki
 
Handling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVMHandling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVMMin-Yih Hsu
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesLuis Goldster
 
Performance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionPerformance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionHaribabu Nandyal Padmanaban
 
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱PgDay.Seoul
 
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍Chris Ohk
 

What's hot (20)

CSW2017 Qinghao tang+Xinlei ying vmware_escape_final
CSW2017 Qinghao tang+Xinlei ying vmware_escape_finalCSW2017 Qinghao tang+Xinlei ying vmware_escape_final
CSW2017 Qinghao tang+Xinlei ying vmware_escape_final
 
GMock framework
GMock frameworkGMock framework
GMock framework
 
NDC15 - 사례로 살펴보는 MSVC 빌드 최적화 팁
NDC15 - 사례로 살펴보는 MSVC 빌드 최적화 팁NDC15 - 사례로 살펴보는 MSVC 빌드 최적화 팁
NDC15 - 사례로 살펴보는 MSVC 빌드 최적화 팁
 
TaaS: Testbeds como Serviço
TaaS: Testbeds como ServiçoTaaS: Testbeds como Serviço
TaaS: Testbeds como Serviço
 
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
 
[오픈소스컨설팅]오픈소스메일시스템
[오픈소스컨설팅]오픈소스메일시스템[오픈소스컨설팅]오픈소스메일시스템
[오픈소스컨설팅]오픈소스메일시스템
 
쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기
 
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
How does PostgreSQL work with disks: a DBA's checklist in detail. PGConf.US 2015
 
청강대 특강 - 프로젝트 제대로 해보기
청강대 특강 - 프로젝트 제대로 해보기청강대 특강 - 프로젝트 제대로 해보기
청강대 특강 - 프로젝트 제대로 해보기
 
gcc and friends
gcc and friendsgcc and friends
gcc and friends
 
[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정
[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정
[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정
 
spinlock.pdf
spinlock.pdfspinlock.pdf
spinlock.pdf
 
S emb t13-freertos
S emb t13-freertosS emb t13-freertos
S emb t13-freertos
 
Spring Boot Actuator 2.0 & Micrometer
Spring Boot Actuator 2.0 & MicrometerSpring Boot Actuator 2.0 & Micrometer
Spring Boot Actuator 2.0 & Micrometer
 
Handling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVMHandling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVM
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Performance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionPerformance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage Collection
 
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
 
Linux Memory
Linux MemoryLinux Memory
Linux Memory
 
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
 

Viewers also liked

Dependency Injection in C++ (Community Days 2015)
Dependency Injection in C++ (Community Days 2015)Dependency Injection in C++ (Community Days 2015)
Dependency Injection in C++ (Community Days 2015)Daniele Pallastrelli
 
C++ Dependency Management 2.0
C++ Dependency Management 2.0C++ Dependency Management 2.0
C++ Dependency Management 2.0Patrick Charrier
 
CMake - Introduction and best practices
CMake - Introduction and best practicesCMake - Introduction and best practices
CMake - Introduction and best practicesDaniel Pfeifer
 
CMake: Improving Software Quality and Process
CMake: Improving Software Quality and ProcessCMake: Improving Software Quality and Process
CMake: Improving Software Quality and ProcessMarcus Hanwell
 
Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014biicode
 
Multithreading with Boost Thread and Intel TBB
Multithreading with Boost Thread and Intel TBBMultithreading with Boost Thread and Intel TBB
Multithreading with Boost Thread and Intel TBBPatrick Charrier
 
Long Life Software
Long Life SoftwareLong Life Software
Long Life SoftwareMike Long
 
Water alternating gas (WAG) - A Enhanced Oil Recovery technique
Water alternating gas (WAG) - A Enhanced Oil Recovery techniqueWater alternating gas (WAG) - A Enhanced Oil Recovery technique
Water alternating gas (WAG) - A Enhanced Oil Recovery techniqueIbrahim Muhammad
 
Intelligent well completio nm
Intelligent well completio nmIntelligent well completio nm
Intelligent well completio nmbasil_c
 
Intelligent well completion
Intelligent well completionIntelligent well completion
Intelligent well completionAkshaya Mishra
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency InjectionTheo Jungeblut
 
Agile for Embedded & System Software Development : Presented by Priyank KS
Agile for Embedded & System Software Development : Presented by Priyank KS Agile for Embedded & System Software Development : Presented by Priyank KS
Agile for Embedded & System Software Development : Presented by Priyank KS oGuild .
 
Interfaces to ubiquitous computing
Interfaces to ubiquitous computingInterfaces to ubiquitous computing
Interfaces to ubiquitous computingswati sonawane
 
iBeacons: Security and Privacy?
iBeacons: Security and Privacy?iBeacons: Security and Privacy?
iBeacons: Security and Privacy?Jim Fenton
 
Demystifying dependency Injection: Dagger and Toothpick
Demystifying dependency Injection: Dagger and ToothpickDemystifying dependency Injection: Dagger and Toothpick
Demystifying dependency Injection: Dagger and ToothpickDanny Preussler
 
Agile London: Industrial Agility, How to respond to the 4th Industrial Revolu...
Agile London: Industrial Agility, How to respond to the 4th Industrial Revolu...Agile London: Industrial Agility, How to respond to the 4th Industrial Revolu...
Agile London: Industrial Agility, How to respond to the 4th Industrial Revolu...Paolo Sammicheli
 

Viewers also liked (20)

Dependency Injection in C++ (Community Days 2015)
Dependency Injection in C++ (Community Days 2015)Dependency Injection in C++ (Community Days 2015)
Dependency Injection in C++ (Community Days 2015)
 
C++ Dependency Management 2.0
C++ Dependency Management 2.0C++ Dependency Management 2.0
C++ Dependency Management 2.0
 
CMake - Introduction and best practices
CMake - Introduction and best practicesCMake - Introduction and best practices
CMake - Introduction and best practices
 
CMake: Improving Software Quality and Process
CMake: Improving Software Quality and ProcessCMake: Improving Software Quality and Process
CMake: Improving Software Quality and Process
 
Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Multithreading with Boost Thread and Intel TBB
Multithreading with Boost Thread and Intel TBBMultithreading with Boost Thread and Intel TBB
Multithreading with Boost Thread and Intel TBB
 
Long Life Software
Long Life SoftwareLong Life Software
Long Life Software
 
Water alternating gas (WAG) - A Enhanced Oil Recovery technique
Water alternating gas (WAG) - A Enhanced Oil Recovery techniqueWater alternating gas (WAG) - A Enhanced Oil Recovery technique
Water alternating gas (WAG) - A Enhanced Oil Recovery technique
 
Intelligent well completio nm
Intelligent well completio nmIntelligent well completio nm
Intelligent well completio nm
 
Intelligent well completion
Intelligent well completionIntelligent well completion
Intelligent well completion
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
 
Agile for Embedded & System Software Development : Presented by Priyank KS
Agile for Embedded & System Software Development : Presented by Priyank KS Agile for Embedded & System Software Development : Presented by Priyank KS
Agile for Embedded & System Software Development : Presented by Priyank KS
 
3.7 heap sort
3.7 heap sort3.7 heap sort
3.7 heap sort
 
Interfaces to ubiquitous computing
Interfaces to ubiquitous computingInterfaces to ubiquitous computing
Interfaces to ubiquitous computing
 
iBeacons: Security and Privacy?
iBeacons: Security and Privacy?iBeacons: Security and Privacy?
iBeacons: Security and Privacy?
 
Intelligent well completions
Intelligent well completionsIntelligent well completions
Intelligent well completions
 
Demystifying dependency Injection: Dagger and Toothpick
Demystifying dependency Injection: Dagger and ToothpickDemystifying dependency Injection: Dagger and Toothpick
Demystifying dependency Injection: Dagger and Toothpick
 
Dependency Injection with Apex
Dependency Injection with ApexDependency Injection with Apex
Dependency Injection with Apex
 
Agile London: Industrial Agility, How to respond to the 4th Industrial Revolu...
Agile London: Industrial Agility, How to respond to the 4th Industrial Revolu...Agile London: Industrial Agility, How to respond to the 4th Industrial Revolu...
Agile London: Industrial Agility, How to respond to the 4th Industrial Revolu...
 

Similar to Going native with less coupling: Dependency Injection in C++

Meetup SkillValue - Angular 6 : Bien démarrer son application
Meetup SkillValue - Angular 6 : Bien démarrer son applicationMeetup SkillValue - Angular 6 : Bien démarrer son application
Meetup SkillValue - Angular 6 : Bien démarrer son applicationThibault Even
 
generate IP CORES
generate IP CORESgenerate IP CORES
generate IP CORESguest296013
 
Contiki Operating system tutorial
Contiki Operating system tutorialContiki Operating system tutorial
Contiki Operating system tutorialSalah Amean
 
Adding Love to an API (or How to Expose C++ in Unity)
Adding Love to an API (or How to Expose C++ in Unity)Adding Love to an API (or How to Expose C++ in Unity)
Adding Love to an API (or How to Expose C++ in Unity)Unity Technologies
 
8.3 program structure (1 hour)
8.3 program structure (1 hour)8.3 program structure (1 hour)
8.3 program structure (1 hour)akmalfahmi
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slidesDavid Barreto
 
Idea to Production - with Gitlab and Kubernetes
Idea to Production  - with Gitlab and KubernetesIdea to Production  - with Gitlab and Kubernetes
Idea to Production - with Gitlab and KubernetesSimon Dittlmann
 
The Ring programming language version 1.3 book - Part 62 of 88
The Ring programming language version 1.3 book - Part 62 of 88The Ring programming language version 1.3 book - Part 62 of 88
The Ring programming language version 1.3 book - Part 62 of 88Mahmoud Samir Fayed
 
Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)Peter R. Egli
 
The Ring programming language version 1.2 book - Part 59 of 84
The Ring programming language version 1.2 book - Part 59 of 84The Ring programming language version 1.2 book - Part 59 of 84
The Ring programming language version 1.2 book - Part 59 of 84Mahmoud Samir Fayed
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...Andrey Karpov
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14Matthieu Garrigues
 
The Ring programming language version 1.7 book - Part 82 of 196
The Ring programming language version 1.7 book - Part 82 of 196The Ring programming language version 1.7 book - Part 82 of 196
The Ring programming language version 1.7 book - Part 82 of 196Mahmoud Samir Fayed
 
embeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptxembeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptxsangeetaSS
 
The Ring programming language version 1.4 book - Part 22 of 30
The Ring programming language version 1.4 book - Part 22 of 30The Ring programming language version 1.4 book - Part 22 of 30
The Ring programming language version 1.4 book - Part 22 of 30Mahmoud Samir Fayed
 
cscript_controller.pdf
cscript_controller.pdfcscript_controller.pdf
cscript_controller.pdfVcTrn1
 
15LLP108_Demo4_LedBlinking.pdf1. Introduction In D.docx
15LLP108_Demo4_LedBlinking.pdf1. Introduction In D.docx15LLP108_Demo4_LedBlinking.pdf1. Introduction In D.docx
15LLP108_Demo4_LedBlinking.pdf1. Introduction In D.docxfelicidaddinwoodie
 

Similar to Going native with less coupling: Dependency Injection in C++ (20)

Meetup SkillValue - Angular 6 : Bien démarrer son application
Meetup SkillValue - Angular 6 : Bien démarrer son applicationMeetup SkillValue - Angular 6 : Bien démarrer son application
Meetup SkillValue - Angular 6 : Bien démarrer son application
 
generate IP CORES
generate IP CORESgenerate IP CORES
generate IP CORES
 
Contiki Operating system tutorial
Contiki Operating system tutorialContiki Operating system tutorial
Contiki Operating system tutorial
 
Adding Love to an API (or How to Expose C++ in Unity)
Adding Love to an API (or How to Expose C++ in Unity)Adding Love to an API (or How to Expose C++ in Unity)
Adding Love to an API (or How to Expose C++ in Unity)
 
8.3 program structure (1 hour)
8.3 program structure (1 hour)8.3 program structure (1 hour)
8.3 program structure (1 hour)
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
 
Idea to Production - with Gitlab and Kubernetes
Idea to Production  - with Gitlab and KubernetesIdea to Production  - with Gitlab and Kubernetes
Idea to Production - with Gitlab and Kubernetes
 
The Ring programming language version 1.3 book - Part 62 of 88
The Ring programming language version 1.3 book - Part 62 of 88The Ring programming language version 1.3 book - Part 62 of 88
The Ring programming language version 1.3 book - Part 62 of 88
 
Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)
 
Cpp
CppCpp
Cpp
 
Angular 2 in-1
Angular 2 in-1 Angular 2 in-1
Angular 2 in-1
 
The Ring programming language version 1.2 book - Part 59 of 84
The Ring programming language version 1.2 book - Part 59 of 84The Ring programming language version 1.2 book - Part 59 of 84
The Ring programming language version 1.2 book - Part 59 of 84
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
 
2621008 - C++ 1
2621008 -  C++ 12621008 -  C++ 1
2621008 - C++ 1
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14
 
The Ring programming language version 1.7 book - Part 82 of 196
The Ring programming language version 1.7 book - Part 82 of 196The Ring programming language version 1.7 book - Part 82 of 196
The Ring programming language version 1.7 book - Part 82 of 196
 
embeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptxembeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptx
 
The Ring programming language version 1.4 book - Part 22 of 30
The Ring programming language version 1.4 book - Part 22 of 30The Ring programming language version 1.4 book - Part 22 of 30
The Ring programming language version 1.4 book - Part 22 of 30
 
cscript_controller.pdf
cscript_controller.pdfcscript_controller.pdf
cscript_controller.pdf
 
15LLP108_Demo4_LedBlinking.pdf1. Introduction In D.docx
15LLP108_Demo4_LedBlinking.pdf1. Introduction In D.docx15LLP108_Demo4_LedBlinking.pdf1. Introduction In D.docx
15LLP108_Demo4_LedBlinking.pdf1. Introduction In D.docx
 

Recently uploaded

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 

Recently uploaded (20)

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 

Going native with less coupling: Dependency Injection in C++

  • 1. www.italiancpp.org Going native with less coupling Dependency Injection in C++
  • 2. Italian C++ Community Style 1: [Fake] OO Design i=2 CONTROLLER / MANAGER Dumb object Dumb object Dumb object Dumb object Dumb object Dumb object Dumb object Dumb object
  • 3. Italian C++ Community Style 2: [True] OO design i=3 Smart Object Smart Object Smart Object Smart Object Smart Object Smart Object Smart Object Smart Object Smart Object Smart Object Smart Object Smart Object Smart Object Smart Object
  • 4. Italian C++ Community OO Architecture Benefits i=4 Up Scalability (extension) Down Scalability (contraction) Reusability Safety (testability)
  • 5. Italian C++ Community i=5 The Wiring Issue In a True Modular Architecture, wiring is critical
  • 6. Italian C++ Community The Wiring Issue When you've got a Good Architecture, you deal with requirements changes by adding/removing/substituting objects So, we need a simple way to: Change the type of the objects Create new objects Modify the wiring of the objects i=6
  • 7. Italian C++ Community i=7 Life without a CONTROLLER Example taken from: Carlo Pescio's blog – March 2012
  • 8. Italian C++ Community First Design i=8 MinePlant SumpPump +Drain() PumpEngine +On() +Off() DigitalOutput +Write() GasSensor <<interface>> +IsCritical() GasAlarm +Watch() 1..* Alarm +On() +Off() SafeEngine
  • 9. Italian C++ Community Requirements Change i=9 MinePlant SumpPump +Drain() PumpEngine +On() +Off() DigitalOutput +Write() GasSensor <<interface>> +IsCritical() GasAlarm +Watch() 1..* Alarm +On() +Off() SafeEngine
  • 10. Italian C++ Community Extension The design is robust: I only need to add a class But… Who creates SafeEngine instead of PumpEngine? How does SafeEngine get the pointer to the GasSensor (the same used by GasAlarm)? i=10
  • 11. Italian C++ Community Solution #1: Local Creation Each class creates its own dependencies i=11
  • 12. Italian C++ Community i=12 MinePlant SumpPump +Drain() PumpEngine +On() +Off() DigitalOutput +Write() GasSensor <<interface>> +IsCritical() GasAlarm +Watch() 1..* Alarm +On() +Off() SafeEngine <<create>>
  • 13. Italian C++ Community Solution #1: Consequences The SumpPump constructor creates a SafeEngine instead of a PumpEngine. … but SafeEngine needs a pointer to the GasSensor instance already used by GasAlarm. So, we must pass it as a parameter to SumpPump constructor. i=13
  • 14. Italian C++ Community Solution #1: Properties If I need to change the concrete type, I have to modify the client. It's difficult to reuse the same client class (even in the same application). i=14
  • 15. Italian C++ Community Solution #1: Summary SafeEngine class added SumpPump constructor modified MinePlant modified i=15
  • 16. Italian C++ Community Solution #2: Factory (not the GoF factory) Create objects without exposing the instantiation logic to the client i=16
  • 17. Italian C++ Community i=17 <<create>>
  • 18. Italian C++ Community Solution #2: Consequences The SumpPump constructor takes a Factory as parameter. PumpEngineFactory instantiates a PumpEngine. SafeEngineFactory instantiates a SafeEngine. SafeEngine still needs a pointer to the GasSensor instance already used by GasAlarm, so we must pass it to the SafeEngineFactory constructor. i=18
  • 19. Italian C++ Community Solution #2: Summary SafeEngine class added SafeEngineFactory added MinePlant modified i=19
  • 20. Italian C++ Community Solution #3: Service Locator It’s a registry containing the instances to use i=20
  • 21. Italian C++ Community Solution #3: Service Locator i=21 class ServiceLocator { public: static ServiceLocator& Instance(); shared_ptr< PumpEngine > Engine(); void Engine( const shared_ptr< PumpEngine >& engine ); private: ... };
  • 22. Italian C++ Community Solution #3: Service Locator i=22 // MinePlant: auto e = make_shared< SafeEngine >( engineOutput, gasSensor ); ServiceLocator::Instance().Engine( e ); // SumpPump: SumpPump::SumpPump() : engine( ServiceLocator::Instance().Engine() ) { }
  • 23. Italian C++ Community Solution #3: Properties Clients aware of the locator Dependencies not explicit / evident Dependencies not checked by compiler i=23
  • 24. Italian C++ Community Solution #3: Summary SafeEngine class added MinePlant modified i=24
  • 25. Italian C++ Community Solution #4: Dependency Injection Dependency Injection is when you have something setting the dependencies for you. i=25
  • 26. Italian C++ Community Solution #4: Dependency Injection Classes don't create their own dependencies They're passed from outside i=26
  • 27. Italian C++ Community Dependency Injection i=27 auto gasSensor = ... auto alarmOutput = make_shared<DigitalOutput>("/dev/ttyS0"); auto alarm = make_shared<Alarm>(alarmOutput); auto gasAlarm = make_shared<GasAlarm>(gasSensor,alarm); auto engineOutput = make_shared<DigitalOutput>("/dev/ttyS1"); auto engine = make_shared<PumpEngine>(engineOutput); auto pump = make_shared<SumpPump>(engine);
  • 28. Italian C++ Community Dependency Injection i=28 auto gasSensor = ... auto alarmOutput = make_shared<DigitalOutput>("/dev/ttyS0"); auto alarm = make_shared<Alarm>(alarmOutput); auto gasAlarm = make_shared<GasAlarm>(gasSensor,alarm); auto engineOutput = make_shared<DigitalOutput>("/dev/ttyS1"); // auto engine = make_shared<PumpEngine>(engineOutput); auto engine = make_shared<SafeEngine>(engineOutput,gasSensor); auto pump = make_shared<SumpPump>(engine);
  • 29. Italian C++ Community Solution #4: Properties Complete separation between: application logic (classes) wiring (main/builder) i=29
  • 30. Italian C++ Community Solution #4: Summary SafeEngine class added MinePlant modified (one liner) i=30
  • 31. Italian C++ Community i=31 Can we do BETTER SafeEngine must be added anyway. … can we remove the one liner in MinePlant? ?
  • 32. Italian C++ Community i=32 Configuration DrivenWIRING moving creation and wiring outside the code, in a configuration file
  • 33. Italian C++ Community Why? To easily get extensibility/contraction (without having to touch zillion files and recompile everything) i=33
  • 34. Italian C++ Community From Identifiers to Strings Improving Previous Solution: Objects creation from string Objects identified by name Objects connected by name i=34
  • 35. Italian C++ Community Run-time Reflection Missing… Create("Foo") vs new Foo Enumerate the dependencies “Inject” the right object address in a class dependency i=35
  • 36. Italian C++ Community Solution #5: Dependency Injection + Dependency Injection is when you have something setting the dependencies for you. …this something is usually a framework. i=36
  • 37. Italian C++ Community Existing libraries (C++) i=37 QtIOCContainer Sauce DICPP Hypodermic2 Pococapsule Main issues: Compile time injection only Code generators needed
  • 38. Italian C++ Community Enter Wallaroo Library i=38 wallaroo.googlecode.com wallarooC++ Dependency Injection
  • 39. Italian C++ Community Creating objects i=39 Catalog catalog; ... catalog.Create("alarmOutput","DigitalOutput","/dev/ttyS0"); catalog.Create("alarm","Alarm"); catalog.Create("gasAlarm","GasAlarm"); catalog.Create("engineOutput","DigitalOutput","/dev/ttyS1"); catalog.Create("pump","SumpPump"); catalog.Create("engine","SafeEngine");
  • 40. Italian C++ Community Creating objects (from cfg) i=40 <parts> <part> <name>pump</name> <class>SumpPump</class> </part> <part> <name>engine</name> <class>SafeEngine</class> </part> </parts> ... Catalog catalog; XmlConfiguration file("wiring.xml"); file.Fill( catalog ); ...
  • 41. Italian C++ Community Object lookup by name i=41 shared_ptr< SumpPump > pump = catalog[ "pump" ];
  • 42. Italian C++ Community Connect Things by name (DSL) i=42 Catalog catalog; // fill catalog ... use(catalog["alarmOutput"]).as("out").of(catalog["alarm" ]); use(catalog["safeEngine"]).as("engine").of(catalog["pump"]);
  • 43. Italian C++ Community Connect Things by name (DSL) i=43 Catalog catalog; // fill catalog ... wallaroo_within( catalog ) { use( "alarmOutput" ).as( "out" ).of( "alarm" ); use( "safeEngine" ).as( "engine" ).of( "pump" ); }
  • 44. Italian C++ Community Connect Things by name (from cfg) i=44 <wiring> <wire> <source>alarm</source> <dest>alarmOutput</dest> <collaborator>out</collaborator> </wire> <wire> <source>pump</source> <dest>safeEngine</dest> <collaborator>engine</collaborator> </wire> </wiring> Catalog catalog; ... XmlConfiguration file( "wiring.xml" ); file.Fill( catalog ); catalog.CheckWiring(); ...
  • 45. Italian C++ Community Class Declaration i=45 #include "wallaroo/registered.h" using namespace wallaroo; class SumpPump : public Part { public: SumpPump( int id ); private: Collaborator< Engine > engine; };
  • 46. Italian C++ Community Class Registration i=46 WALLAROO_REGISTER( SumpPump, int ) SumpPump::SumpPump( int id ) : engine( "engine", RegistrationToken() ) { ... } // other methods definition here ...
  • 47. Italian C++ Community Shared Libraries – AKA plugins (code) i=47 Plugin::Load( "safeengine" + Plugin::Suffix() ); // Plugin::Suffix() expands to .dll or .so according to the OS
  • 48. Italian C++ Community Shared Libraries – AKA plugins (cfg) i=48 <plugins> <shared>safeengine</shared> </plugins> Catalog catalog; XmlConfiguration file( "wiring.xml" ); // load the shared libraries specified in the configuration file: file.LoadPlugins(); file.Fill( catalog ); // throws a WiringError exception if any dependency is missing: catalog.CheckWiring();
  • 49. Italian C++ Community Collections i=49 class Car : public wallaroo::Part { ... private: Collaborator< Engine > engine; Collaborator< AirConditioning, optional > airConditioning; Collaborator< Airbag, collection > airbags; Collaborator< Speaker, collection, std::list > speakers; Collaborator< Seat, bounded_collection< 2, 6 > > seats; };
  • 50. Italian C++ Community Checks i=50 if ( !catalog.IsWiringOk() ) { // error handling } catalog.CheckWiring() // throws exception
  • 51. Italian C++ Community Initialization i=51 class Part { ... public: virtual void Init() {} ... }; catalog.Init() // calls Part::Init for each part in catalog
  • 52. Italian C++ Community Wallaroo Internals WALLAROO_REGISTER declares a static object. Its constructor creates a factory and puts it in a table, with the class name as key. Catalog::Create uses the factory to put a new instance in the catalog. wallaroo::Part has a table of <name, Collaborator> i=52
  • 53. Italian C++ Community Wallaroo Internals shared_ptr< Foo > foo = catalog[ “foo” ]; catalog[ “foo” ] returns a class that defines operator shared_ptr< T >() Collaborator uses weak_ptr for the dependency Collaborator defines operator shared_ptr() and operator->() i=53
  • 54. Italian C++ Community Wallaroo Internals i=54 wallaroo_within( catalog ) { use("alarmOutput").as("out").of("alarm"); use("safeEngine").as("engine").of("pump"); } for ( Context c(catalog);c.FirstTime();c.Terminate() ) { use("alarmOutput").as("out").of("alarm"); use("safeEngine").as("engine").of("pump"); }
  • 55. Italian C++ Community Wallaroo Strengths Lightweight (header file only) Portable Type Safe DSL syntax for object creation and wiring Configuration driven wiring (xml and json) Shared library support (plugin) C++11/14 or boost interface No code generators i=55
  • 56. Italian C++ Community Design is a balance of forces Intrusive VS Non Intrusive Non Intrusive Solutions can manage existing classes but require code generators for configuration driven wiring i=56
  • 57. Italian C++ Community Design is a balance of forces Configuration-driven wiring VS static type checking By moving the wiring in a configuration file, we give up the static type checking. But it’s ok, since you build your system at startup. i=57
  • 58. Italian C++ Community Action Points Real OOD (no controllers / managers) Manual Dependency Injection Wallaroo (configuration-driven wiring) i=58
  • 59. Italian C++ Community References & Credits Me: @DPallastrelli Me: it.linkedin.com/in/pallad Rate me: https://joind.in/12277 Wallaroo: wallaroo.googlecode.com i=59 MinePlant example from Carlo Pescio's blog (http://www.carlopescio.com/2012/03/life- without-controller-case-1.html) Wiring Picture: By Gael Mace (Own work (Personal photograph)) [CC-BY-3.0 (http://creativecommons.org/licenses/by/3.0)], via Wikimedia Commons