SlideShare a Scribd company logo
Carlo Pescio http://carlopescio.com http://eptacom.net
Carlo Pescio
An overly simple, C++ idiomatic
pattern language for message-
based product families
overly simple
pattern language
based product families
message-
C++ idiomatic
Carlo Pescio http://carlopescio.com http://eptacom.net
Time-proven
- Used many times over ~20y
- Used in small (PIC 32 w/ KB of RAM) embedded systems
- Used in “big” (i7 w/ GB of RAM) embedded systems
- N x 100K units around the world using this stuff 
Carlo Pescio http://carlopescio.com http://eptacom.net
good design??
- Principles
- Patterns
- Dogma
- Paradigm
- Method
- Technology
Forces -> Response
Carlo Pescio http://carlopescio.com http://eptacom.net
Product family
Carlo Pescio http://carlopescio.com http://eptacom.net
Product
a subset of a “feature set”
Defined extensionally : P = { F1, …, Fp }
Most likely dynamic over time
- Products can be standard or custom
- | P | is “relevant”
Carlo Pescio http://carlopescio.com http://eptacom.net
Product family
a set of products
Defined extensionally : F = { P1, …, Pf }
Dynamic over time
| Pi ∩Pj | ≈ ∑| Pi |_____
f
- | F | is “relevant”
Carlo Pescio http://carlopescio.com http://eptacom.net
Approaches
- Many, but mostly:
- Full-blown + configuration
- Selected features only
Carlo Pescio http://carlopescio.com http://eptacom.net
“expansive force”
“good response”
- New feature -> New code
- Grow / shrink product
- include / remove file
- Add product to family
- Choose file set
Product growth
Family growth
Feature set growth
Carlo Pescio http://carlopescio.com http://eptacom.net
“bad response”
Custom code, “feature aware” code for each product
|F| “relevant” => lots of custom artifacts
|P| “relevant” => each artifact is “relevant”
| Pi ∩Pj | ≈ ∑| Pi | => custom yet highly similar
________
f
|F| and |P| unstable and usually growing => maintenance cost
Common traps: switch/case, pattern matching, case classes, sum
types, builders, … (anything “enumerative” in nature)
Carlo Pescio http://carlopescio.com http://eptacom.net
Context
Carlo Pescio http://carlopescio.com http://eptacom.net
class MessageHandler // or Dispatcher
{
void handle( const Message& m )
{
switch( m.getSubsystem() )
{
case SS1 :
{
switch( m.getCommand() )
{
case CMD1:
{
// now what?
}
}
}
}
}
}
The ugliness
- Ugly naming
- Can’t share among products
- Maintenance black hole
- Same issue with pattern matching
Carlo Pescio http://carlopescio.com http://eptacom.net
Half-hearted
I know, I’ll use a map of commands!
MessageHandler
Message -> SID,CID,params
CmdMap : (SID,CID) -> Command
Command -> Execute( params )
Ok, who is filling the map?
- A “main”
- A “factory”
still the same problem /
shape
- A “configuration file”
- not idiomatic (reflection?)
- better for “full-blown”
- [ dynamic loading not available
everywhere, e.g. PIC 32]
Carlo Pescio http://carlopescio.com http://eptacom.net
A 1st idiomatic notion
Self-instantiating object
Avoid the common trap of a single artifact which knows many objects.
Add a class (artifact) -> Get an object (run-time)
The object is born before main is executed. Avoids threading issues as well.
Idiomatic: can’t do this in Java or C#, they only got lazy statics.
Carlo Pescio http://carlopescio.com http://eptacom.net
Code: overly simple
class SelfCreating
{
private:
SelfCreating()
{
std::cout << "I'm the magical self-creating object" << std::endl;
}
static SelfCreating instance;
};
#include "SelfCreating.h"
SelfCreating SelfCreating::instance;
int main()
{
cout << "I'm the main function" << endl;
return 0;
}
Carlo Pescio http://carlopescio.com http://eptacom.net
The self-creating singleton
Useful outside this restricted application.
The C++ idiomatic solution to the real hard question:
who creates the creator? << it creates itself (seems just right too)
See:
prototype
abstract factory
factory method
etc.
Carlo Pescio http://carlopescio.com http://eptacom.net
Bring in some domain
A command is a self-instantiating, stateless singleton
- Self instantiating: no one needs to “know all the commands”
- Commands register themselves with a catalog
reversing the dependency
- Being stateless is not strictly necessary, but it’s often the right choice
commands are ok with being stateless anyway
Carlo Pescio http://carlopescio.com http://eptacom.net
A singleton (booooo!!!)
Stateless, immutable, single function -> it’s a function (ooohhhhh!!!!!)
Added Value: the singleton constructor will register the function in a catalog
that’s the magic functions can’t do
But the catalog must be a singleton too, and born before (ain’t that difficult?)
Carlo Pescio http://carlopescio.com http://eptacom.net
Commands & subsystem
Being realistic:
same command code in different susbsystems should be ok
Therefore: a command catalog for each subsystem
Therefore: the [concrete] command should know its own subsystem
it’s OK, it’s the opposite that we do not want (ss->cmd)
Code: simple enough
class Command
{
public:
virtual ~Command()
{
}
virtual void Process(
const char* payload) = 0;
};
template<class SS, class CMD> class
RegisteredCommand : public Command
{
protected:
RegisteredCommand()
{
CommandCatalog<SS::SID>::
RegisterCommand(CMD::CID, instance);
}
private:
// eager singleton - MUST be eager
static CMD instance;
};
template<class SS, class CMD> CMD
RegisteredCommand<SS,CMD>::instance;
CRTP
(2nd Idiomatic notion)
Carlo Pescio http://carlopescio.com http://eptacom.net
Code: simple enough
class StartEngineCMD : public
RegisteredCommand< EngineSS, StartEngineCMD >
{
public:
static const int CID = 2;
void Process(const char* payload) override;
private:
friend class RegisteredCommand< EngineSS, StartEngineCMD >;
StartEngineCMD();
};
Carlo Pescio http://carlopescio.com http://eptacom.net
UML diagram (in 2017 ?! :-)
Type
erasure
Carlo Pescio http://carlopescio.com http://eptacom.net
A 3rd idiomatic notion
A command catalog is a stateful, semi-immutable lazy singleton
- Lazy: simplest way to solve the initialization order problem
commands are eagerly created before main is started,
the first command creates the catalog as well
- The catalog is read-only / immutable when the main is started
all mutations happen in a single thread before main is called
thread-safe, read-only access after that (don’t worry – live happy)
Code: again, overly simple
template< int SID > class CommandCatalog
{
public:
static void RegisterCommand(int CID, Command& c)
{
auto& r = Recipients();
assert(r.find(CID) == r.end());
std::pair< int, Command& > p(CID, c);
r.insert(p);
}
private:
static std::map< int, Command& >& Recipients()
{
// lazy singleton - MUST be lazy
static std::map< int, Command& > recipients;
return recipients;
}
};
// later
// static bool DeliverMessage(
// const Message& m)
Carlo Pescio http://carlopescio.com http://eptacom.net
The haiku
The lazy singleton
is fully constructed
before the eagerest singleton
惰
Carlo Pescio http://carlopescio.com http://eptacom.net
Mocking commands?
Assuming it makes sense – depends on the application
sometimes mocking hardware resources is a better option
If you want a “test build” vs. a “standard build”
trivial, just define mock and std commands, use the makefile
If you want to choose at runtime
create both, register both, enable one [with a command]
one more template parameter will help 
Carlo Pescio http://carlopescio.com http://eptacom.net
Rinse and repeat
- Subsystems are self-creating singleton[s] too
- Subsystems register themselves with a postman / catalog
no one needs to “know all the subsystems”
- The postman is a lazy singleton as well
- See the symmetry: Command<->CommandCatalog, Subsystem<->Postman
sort of, there is 1 catalog per subsystem, but ok
Carlo Pescio http://carlopescio.com http://eptacom.net
there : )
Carlo Pescio http://carlopescio.com http://eptacom.net
Subsystems responsibilities
- Defines its own address (SID, this is in the sample too)
- Owns exclusive HW resources (e.g. a RS485, some I/O, etc.)
- Usually offers some logic to its own commands
- Is usually stateful / mutable: mirrors the state of hw devices
Carlo Pescio http://carlopescio.com http://eptacom.net
A mutable singleton!
- In the sample code, it’s all synchronous, but in a real system, a SS will probably
have its own message queue and a thread. N SS could share 1 thread if reasonable.
- Commands belonging to a SS will be executed in the SS thread.
So even if they call back into the SS, it’s still single -threaded.
We never need to synchronize (except [maybe] the command queue).
- CMD1 in SS1 can send messages to SS2, using the Postman
So it’s also an internal communication channel.
- So, a subsystem is an actor (oooohhh).
- What about mocking?? (same as commands…)
Carlo Pescio http://carlopescio.com http://eptacom.net
A little more code
bool Postman::DeliverMessage(const Message& m)
{
auto r = Recipients();
auto i = r.find(m.SID());
if (i != r.end())
return i->second.OnIncomingMessage(m);
return false;
}
static bool DeliverMessage(const Message& m)
{
auto r = Recipients();
auto i = r.find(m.CID());
if (i != r.end())
{
i->second.Process(m.Payload());
return true;
}
return false;
}
Carlo Pescio http://carlopescio.com http://eptacom.net
Variations
Protocol: encoding, ack/nak, synchronous vs asynchronous answer, etc.
Threading: synchronous, 1 thread per SS, 1 thread * N SS, N thread * 1 SS
Queuing: selective coalescence or not.
Execution: 1 active command, N active commands, background activity
Substitution: Mocking commands, Activable commands, etc.
“Details”: splitting payload parsing and execution (stateful commands, cloning).
Carlo Pescio http://carlopescio.com http://eptacom.net
Why “a pattern language”
“Many patterns form a language”
Trying to generalize will turn this short code into the usual abstract monster
File Name Lines Statements Average Statements per Method
Command.h 12 3 0.0
CommandCatalog.h 41 20 4.0
Message.h 31 10 0.8
Postman.cpp 33 17 3.7
Postman.h 15 7 0.0
RegisteredCommand.h 18 7 1.0
RegisteredSubsystem.h 24 10 1.0
Subsystem.h 14 4 0.0
Carlo Pescio http://carlopescio.com http://eptacom.net
The abstract monster
- Policies everywhere
- Parameters everywhere
- N times longer to account for any possible variability
- Names far removed from domain terminology
- Steep learning curve
- Cross maintenance
VS.
understand the Pattern Language ad adapt on your system
Carlo Pescio http://carlopescio.com http://eptacom.net
PhysicsOfSoftware.com
Notes on Software Design, Chapter 12: Entanglement
http://www.carlopescio.com/2010/11/notes-on-software-design-chapter-12.html
Notes on Software Design, Chapter 13: On Change
http://www.carlopescio.com/2011/02/notes -on-software-design-chapter-14.html
Notes on Software Design, Chapter 14: the Enumeration Law
http://www.carlopescio.com/2011/02/notes -on-software-design-chapter-14.html
On Growth and Software (nCrafts, Paris, May 2016)
Video: http://videos.ncrafts.io/video/167699028
Thanks to the sponsors!
Italian C++ Conference 2017 #itCppCon17
Carlo Pescio http://carlopescio.com http://eptacom.net
Brain-Driven Design
Design your software by squeezing your brain, not by following trends
carlo.pescio@gmail.com

More Related Content

What's hot

Using the Power to Prove
Using the Power to ProveUsing the Power to Prove
Using the Power to Prove
Kazuho Oku
 
도커 없이 컨테이너 만들기 4편 네트워크네임스페이스 (2)
도커 없이 컨테이너 만들기 4편 네트워크네임스페이스 (2)도커 없이 컨테이너 만들기 4편 네트워크네임스페이스 (2)
도커 없이 컨테이너 만들기 4편 네트워크네임스페이스 (2)
Sam Kim
 
Unix Programming with Perl 2
Unix Programming with Perl 2Unix Programming with Perl 2
Unix Programming with Perl 2
Kazuho Oku
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects
Andrey Karpov
 
Unix Programming with Perl
Unix Programming with PerlUnix Programming with Perl
Unix Programming with Perl
Kazuho Oku
 
start_printf: dev/ic/com.c comstart()
start_printf: dev/ic/com.c comstart()start_printf: dev/ic/com.c comstart()
start_printf: dev/ic/com.c comstart()
Kiwamu Okabe
 
Fun with errors? - Clojure Finland Meetup 26.3.2019 Tampere
Fun with errors? - Clojure Finland Meetup 26.3.2019 TampereFun with errors? - Clojure Finland Meetup 26.3.2019 Tampere
Fun with errors? - Clojure Finland Meetup 26.3.2019 Tampere
Metosin Oy
 
Erlangfactory
ErlangfactoryErlangfactory
Erlangfactory
Ezra Zygmuntowicz
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from inside
julien pauli
 
TimeCryption
TimeCryptionTimeCryption
TimeCryption
Ange Albertini
 
WebSummit 2015 - Gopher it
WebSummit 2015 - Gopher itWebSummit 2015 - Gopher it
WebSummit 2015 - Gopher it
Gautam Rege
 
Open Source Debugging v1.3.2
Open Source Debugging v1.3.2Open Source Debugging v1.3.2
Open Source Debugging v1.3.2
Matthew McCullough
 
Connecting C++ and JavaScript on the Web with Embind
Connecting C++ and JavaScript on the Web with EmbindConnecting C++ and JavaScript on the Web with Embind
Connecting C++ and JavaScript on the Web with Embind
Chad Austin
 
play framework async with scala
play framework async with scalaplay framework async with scala
play framework async with scala
vuhaininh88
 
Make container without_docker_6-overlay-network_1
Make container without_docker_6-overlay-network_1 Make container without_docker_6-overlay-network_1
Make container without_docker_6-overlay-network_1
Sam Kim
 
Cloud Erlang
Cloud ErlangCloud Erlang
Cloud Erlang
Ngoc Dao
 

What's hot (16)

Using the Power to Prove
Using the Power to ProveUsing the Power to Prove
Using the Power to Prove
 
도커 없이 컨테이너 만들기 4편 네트워크네임스페이스 (2)
도커 없이 컨테이너 만들기 4편 네트워크네임스페이스 (2)도커 없이 컨테이너 만들기 4편 네트워크네임스페이스 (2)
도커 없이 컨테이너 만들기 4편 네트워크네임스페이스 (2)
 
Unix Programming with Perl 2
Unix Programming with Perl 2Unix Programming with Perl 2
Unix Programming with Perl 2
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects
 
Unix Programming with Perl
Unix Programming with PerlUnix Programming with Perl
Unix Programming with Perl
 
start_printf: dev/ic/com.c comstart()
start_printf: dev/ic/com.c comstart()start_printf: dev/ic/com.c comstart()
start_printf: dev/ic/com.c comstart()
 
Fun with errors? - Clojure Finland Meetup 26.3.2019 Tampere
Fun with errors? - Clojure Finland Meetup 26.3.2019 TampereFun with errors? - Clojure Finland Meetup 26.3.2019 Tampere
Fun with errors? - Clojure Finland Meetup 26.3.2019 Tampere
 
Erlangfactory
ErlangfactoryErlangfactory
Erlangfactory
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from inside
 
TimeCryption
TimeCryptionTimeCryption
TimeCryption
 
WebSummit 2015 - Gopher it
WebSummit 2015 - Gopher itWebSummit 2015 - Gopher it
WebSummit 2015 - Gopher it
 
Open Source Debugging v1.3.2
Open Source Debugging v1.3.2Open Source Debugging v1.3.2
Open Source Debugging v1.3.2
 
Connecting C++ and JavaScript on the Web with Embind
Connecting C++ and JavaScript on the Web with EmbindConnecting C++ and JavaScript on the Web with Embind
Connecting C++ and JavaScript on the Web with Embind
 
play framework async with scala
play framework async with scalaplay framework async with scala
play framework async with scala
 
Make container without_docker_6-overlay-network_1
Make container without_docker_6-overlay-network_1 Make container without_docker_6-overlay-network_1
Make container without_docker_6-overlay-network_1
 
Cloud Erlang
Cloud ErlangCloud Erlang
Cloud Erlang
 

Similar to Itacpp.2.la

How to make a large C++-code base manageable
How to make a large C++-code base manageableHow to make a large C++-code base manageable
How to make a large C++-code base manageable
corehard_by
 
[Ruxcon Monthly Sydney 2011] Proprietary Protocols Reverse Engineering : Rese...
[Ruxcon Monthly Sydney 2011] Proprietary Protocols Reverse Engineering : Rese...[Ruxcon Monthly Sydney 2011] Proprietary Protocols Reverse Engineering : Rese...
[Ruxcon Monthly Sydney 2011] Proprietary Protocols Reverse Engineering : Rese...
Moabi.com
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in go
borderj
 
Raising the Bar on Robotics Code Quality
Raising the Bar on Robotics Code QualityRaising the Bar on Robotics Code Quality
Raising the Bar on Robotics Code Quality
Thomas Moulard
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
ComicSansMS
 
Such a weird Processor: messing with opcodes (...and a little bit of PE) (Has...
Such a weird Processor: messing with opcodes (...and a little bit of PE) (Has...Such a weird Processor: messing with opcodes (...and a little bit of PE) (Has...
Such a weird Processor: messing with opcodes (...and a little bit of PE) (Has...
Ange Albertini
 
Boo Manifesto
Boo ManifestoBoo Manifesto
Boo Manifesto
hu hans
 
Checking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameChecking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto Game
Andrey Karpov
 
Compiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual MachinesCompiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual Machines
Eelco Visser
 
ooc - A hybrid language experiment
ooc - A hybrid language experimentooc - A hybrid language experiment
ooc - A hybrid language experiment
Amos Wenger
 
ooc - A hybrid language experiment
ooc - A hybrid language experimentooc - A hybrid language experiment
ooc - A hybrid language experiment
Amos Wenger
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
JavaTpoint.Com
 
Programming Assignment Help
Programming Assignment HelpProgramming Assignment Help
Programming Assignment Help
Programming Homework Help
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
Francesco Casalegno
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
NAVER D2
 
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
apidays
 
[CCC-28c3] Post Memory Corruption Memory Analysis
[CCC-28c3] Post Memory Corruption Memory Analysis[CCC-28c3] Post Memory Corruption Memory Analysis
[CCC-28c3] Post Memory Corruption Memory Analysis
Moabi.com
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
Microsoft Tech Community
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
Microsoft Tech Community
 
Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Eve
guest91855c
 

Similar to Itacpp.2.la (20)

How to make a large C++-code base manageable
How to make a large C++-code base manageableHow to make a large C++-code base manageable
How to make a large C++-code base manageable
 
[Ruxcon Monthly Sydney 2011] Proprietary Protocols Reverse Engineering : Rese...
[Ruxcon Monthly Sydney 2011] Proprietary Protocols Reverse Engineering : Rese...[Ruxcon Monthly Sydney 2011] Proprietary Protocols Reverse Engineering : Rese...
[Ruxcon Monthly Sydney 2011] Proprietary Protocols Reverse Engineering : Rese...
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in go
 
Raising the Bar on Robotics Code Quality
Raising the Bar on Robotics Code QualityRaising the Bar on Robotics Code Quality
Raising the Bar on Robotics Code Quality
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
Such a weird Processor: messing with opcodes (...and a little bit of PE) (Has...
Such a weird Processor: messing with opcodes (...and a little bit of PE) (Has...Such a weird Processor: messing with opcodes (...and a little bit of PE) (Has...
Such a weird Processor: messing with opcodes (...and a little bit of PE) (Has...
 
Boo Manifesto
Boo ManifestoBoo Manifesto
Boo Manifesto
 
Checking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameChecking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto Game
 
Compiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual MachinesCompiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual Machines
 
ooc - A hybrid language experiment
ooc - A hybrid language experimentooc - A hybrid language experiment
ooc - A hybrid language experiment
 
ooc - A hybrid language experiment
ooc - A hybrid language experimentooc - A hybrid language experiment
ooc - A hybrid language experiment
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
 
Programming Assignment Help
Programming Assignment HelpProgramming Assignment Help
Programming Assignment Help
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
 
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
 
[CCC-28c3] Post Memory Corruption Memory Analysis
[CCC-28c3] Post Memory Corruption Memory Analysis[CCC-28c3] Post Memory Corruption Memory Analysis
[CCC-28c3] Post Memory Corruption Memory Analysis
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Eve
 

Recently uploaded

Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
Jhone kinadey
 
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and MoreManyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
narinav14
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
vaishalijagtap12
 
Going AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applicationsGoing AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applications
Alina Yurenko
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
The Third Creative Media
 
What is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdfWhat is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdf
kalichargn70th171
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Peter Caitens
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
Maitrey Patel
 
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
OnePlan Solutions
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
kalichargn70th171
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
kgyxske
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
widenerjobeyrl638
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 

Recently uploaded (20)

Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
 
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and MoreManyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
 
bgiolcb
bgiolcbbgiolcb
bgiolcb
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
 
Going AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applicationsGoing AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applications
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
 
What is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdfWhat is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdf
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
 
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 

Itacpp.2.la

  • 1. Carlo Pescio http://carlopescio.com http://eptacom.net Carlo Pescio An overly simple, C++ idiomatic pattern language for message- based product families overly simple pattern language based product families message- C++ idiomatic
  • 2. Carlo Pescio http://carlopescio.com http://eptacom.net Time-proven - Used many times over ~20y - Used in small (PIC 32 w/ KB of RAM) embedded systems - Used in “big” (i7 w/ GB of RAM) embedded systems - N x 100K units around the world using this stuff 
  • 3. Carlo Pescio http://carlopescio.com http://eptacom.net good design?? - Principles - Patterns - Dogma - Paradigm - Method - Technology Forces -> Response
  • 4. Carlo Pescio http://carlopescio.com http://eptacom.net Product family
  • 5. Carlo Pescio http://carlopescio.com http://eptacom.net Product a subset of a “feature set” Defined extensionally : P = { F1, …, Fp } Most likely dynamic over time - Products can be standard or custom - | P | is “relevant”
  • 6. Carlo Pescio http://carlopescio.com http://eptacom.net Product family a set of products Defined extensionally : F = { P1, …, Pf } Dynamic over time | Pi ∩Pj | ≈ ∑| Pi |_____ f - | F | is “relevant”
  • 7. Carlo Pescio http://carlopescio.com http://eptacom.net Approaches - Many, but mostly: - Full-blown + configuration - Selected features only
  • 8. Carlo Pescio http://carlopescio.com http://eptacom.net “expansive force” “good response” - New feature -> New code - Grow / shrink product - include / remove file - Add product to family - Choose file set Product growth Family growth Feature set growth
  • 9. Carlo Pescio http://carlopescio.com http://eptacom.net “bad response” Custom code, “feature aware” code for each product |F| “relevant” => lots of custom artifacts |P| “relevant” => each artifact is “relevant” | Pi ∩Pj | ≈ ∑| Pi | => custom yet highly similar ________ f |F| and |P| unstable and usually growing => maintenance cost Common traps: switch/case, pattern matching, case classes, sum types, builders, … (anything “enumerative” in nature)
  • 10. Carlo Pescio http://carlopescio.com http://eptacom.net Context
  • 11. Carlo Pescio http://carlopescio.com http://eptacom.net class MessageHandler // or Dispatcher { void handle( const Message& m ) { switch( m.getSubsystem() ) { case SS1 : { switch( m.getCommand() ) { case CMD1: { // now what? } } } } } } The ugliness - Ugly naming - Can’t share among products - Maintenance black hole - Same issue with pattern matching
  • 12. Carlo Pescio http://carlopescio.com http://eptacom.net Half-hearted I know, I’ll use a map of commands! MessageHandler Message -> SID,CID,params CmdMap : (SID,CID) -> Command Command -> Execute( params ) Ok, who is filling the map? - A “main” - A “factory” still the same problem / shape - A “configuration file” - not idiomatic (reflection?) - better for “full-blown” - [ dynamic loading not available everywhere, e.g. PIC 32]
  • 13. Carlo Pescio http://carlopescio.com http://eptacom.net A 1st idiomatic notion Self-instantiating object Avoid the common trap of a single artifact which knows many objects. Add a class (artifact) -> Get an object (run-time) The object is born before main is executed. Avoids threading issues as well. Idiomatic: can’t do this in Java or C#, they only got lazy statics.
  • 14. Carlo Pescio http://carlopescio.com http://eptacom.net Code: overly simple class SelfCreating { private: SelfCreating() { std::cout << "I'm the magical self-creating object" << std::endl; } static SelfCreating instance; }; #include "SelfCreating.h" SelfCreating SelfCreating::instance; int main() { cout << "I'm the main function" << endl; return 0; }
  • 15. Carlo Pescio http://carlopescio.com http://eptacom.net The self-creating singleton Useful outside this restricted application. The C++ idiomatic solution to the real hard question: who creates the creator? << it creates itself (seems just right too) See: prototype abstract factory factory method etc.
  • 16. Carlo Pescio http://carlopescio.com http://eptacom.net Bring in some domain A command is a self-instantiating, stateless singleton - Self instantiating: no one needs to “know all the commands” - Commands register themselves with a catalog reversing the dependency - Being stateless is not strictly necessary, but it’s often the right choice commands are ok with being stateless anyway
  • 17. Carlo Pescio http://carlopescio.com http://eptacom.net A singleton (booooo!!!) Stateless, immutable, single function -> it’s a function (ooohhhhh!!!!!) Added Value: the singleton constructor will register the function in a catalog that’s the magic functions can’t do But the catalog must be a singleton too, and born before (ain’t that difficult?)
  • 18. Carlo Pescio http://carlopescio.com http://eptacom.net Commands & subsystem Being realistic: same command code in different susbsystems should be ok Therefore: a command catalog for each subsystem Therefore: the [concrete] command should know its own subsystem it’s OK, it’s the opposite that we do not want (ss->cmd)
  • 19. Code: simple enough class Command { public: virtual ~Command() { } virtual void Process( const char* payload) = 0; }; template<class SS, class CMD> class RegisteredCommand : public Command { protected: RegisteredCommand() { CommandCatalog<SS::SID>:: RegisterCommand(CMD::CID, instance); } private: // eager singleton - MUST be eager static CMD instance; }; template<class SS, class CMD> CMD RegisteredCommand<SS,CMD>::instance; CRTP (2nd Idiomatic notion)
  • 20. Carlo Pescio http://carlopescio.com http://eptacom.net Code: simple enough class StartEngineCMD : public RegisteredCommand< EngineSS, StartEngineCMD > { public: static const int CID = 2; void Process(const char* payload) override; private: friend class RegisteredCommand< EngineSS, StartEngineCMD >; StartEngineCMD(); };
  • 21. Carlo Pescio http://carlopescio.com http://eptacom.net UML diagram (in 2017 ?! :-) Type erasure
  • 22. Carlo Pescio http://carlopescio.com http://eptacom.net A 3rd idiomatic notion A command catalog is a stateful, semi-immutable lazy singleton - Lazy: simplest way to solve the initialization order problem commands are eagerly created before main is started, the first command creates the catalog as well - The catalog is read-only / immutable when the main is started all mutations happen in a single thread before main is called thread-safe, read-only access after that (don’t worry – live happy)
  • 23. Code: again, overly simple template< int SID > class CommandCatalog { public: static void RegisterCommand(int CID, Command& c) { auto& r = Recipients(); assert(r.find(CID) == r.end()); std::pair< int, Command& > p(CID, c); r.insert(p); } private: static std::map< int, Command& >& Recipients() { // lazy singleton - MUST be lazy static std::map< int, Command& > recipients; return recipients; } }; // later // static bool DeliverMessage( // const Message& m)
  • 24. Carlo Pescio http://carlopescio.com http://eptacom.net The haiku The lazy singleton is fully constructed before the eagerest singleton 惰
  • 25. Carlo Pescio http://carlopescio.com http://eptacom.net Mocking commands? Assuming it makes sense – depends on the application sometimes mocking hardware resources is a better option If you want a “test build” vs. a “standard build” trivial, just define mock and std commands, use the makefile If you want to choose at runtime create both, register both, enable one [with a command] one more template parameter will help 
  • 26. Carlo Pescio http://carlopescio.com http://eptacom.net Rinse and repeat - Subsystems are self-creating singleton[s] too - Subsystems register themselves with a postman / catalog no one needs to “know all the subsystems” - The postman is a lazy singleton as well - See the symmetry: Command<->CommandCatalog, Subsystem<->Postman sort of, there is 1 catalog per subsystem, but ok
  • 27. Carlo Pescio http://carlopescio.com http://eptacom.net there : )
  • 28. Carlo Pescio http://carlopescio.com http://eptacom.net Subsystems responsibilities - Defines its own address (SID, this is in the sample too) - Owns exclusive HW resources (e.g. a RS485, some I/O, etc.) - Usually offers some logic to its own commands - Is usually stateful / mutable: mirrors the state of hw devices
  • 29. Carlo Pescio http://carlopescio.com http://eptacom.net A mutable singleton! - In the sample code, it’s all synchronous, but in a real system, a SS will probably have its own message queue and a thread. N SS could share 1 thread if reasonable. - Commands belonging to a SS will be executed in the SS thread. So even if they call back into the SS, it’s still single -threaded. We never need to synchronize (except [maybe] the command queue). - CMD1 in SS1 can send messages to SS2, using the Postman So it’s also an internal communication channel. - So, a subsystem is an actor (oooohhh). - What about mocking?? (same as commands…)
  • 30. Carlo Pescio http://carlopescio.com http://eptacom.net A little more code bool Postman::DeliverMessage(const Message& m) { auto r = Recipients(); auto i = r.find(m.SID()); if (i != r.end()) return i->second.OnIncomingMessage(m); return false; } static bool DeliverMessage(const Message& m) { auto r = Recipients(); auto i = r.find(m.CID()); if (i != r.end()) { i->second.Process(m.Payload()); return true; } return false; }
  • 31. Carlo Pescio http://carlopescio.com http://eptacom.net Variations Protocol: encoding, ack/nak, synchronous vs asynchronous answer, etc. Threading: synchronous, 1 thread per SS, 1 thread * N SS, N thread * 1 SS Queuing: selective coalescence or not. Execution: 1 active command, N active commands, background activity Substitution: Mocking commands, Activable commands, etc. “Details”: splitting payload parsing and execution (stateful commands, cloning).
  • 32. Carlo Pescio http://carlopescio.com http://eptacom.net Why “a pattern language” “Many patterns form a language” Trying to generalize will turn this short code into the usual abstract monster File Name Lines Statements Average Statements per Method Command.h 12 3 0.0 CommandCatalog.h 41 20 4.0 Message.h 31 10 0.8 Postman.cpp 33 17 3.7 Postman.h 15 7 0.0 RegisteredCommand.h 18 7 1.0 RegisteredSubsystem.h 24 10 1.0 Subsystem.h 14 4 0.0
  • 33. Carlo Pescio http://carlopescio.com http://eptacom.net The abstract monster - Policies everywhere - Parameters everywhere - N times longer to account for any possible variability - Names far removed from domain terminology - Steep learning curve - Cross maintenance VS. understand the Pattern Language ad adapt on your system
  • 34. Carlo Pescio http://carlopescio.com http://eptacom.net PhysicsOfSoftware.com Notes on Software Design, Chapter 12: Entanglement http://www.carlopescio.com/2010/11/notes-on-software-design-chapter-12.html Notes on Software Design, Chapter 13: On Change http://www.carlopescio.com/2011/02/notes -on-software-design-chapter-14.html Notes on Software Design, Chapter 14: the Enumeration Law http://www.carlopescio.com/2011/02/notes -on-software-design-chapter-14.html On Growth and Software (nCrafts, Paris, May 2016) Video: http://videos.ncrafts.io/video/167699028
  • 35. Thanks to the sponsors! Italian C++ Conference 2017 #itCppCon17
  • 36. Carlo Pescio http://carlopescio.com http://eptacom.net Brain-Driven Design Design your software by squeezing your brain, not by following trends carlo.pescio@gmail.com