SlideShare una empresa de Scribd logo
1 de 74
Design Paterns in the
XXI Century
Dmitri Nesteruk
dmitrinesteruk@gmail.com
@dnesteruk
What’s In This Talk?
• Examples of patterns and approaches in OOP design
• Simple decorator
• Composite
• Specification pattern/OCP
• Fluent and Groovy-style builders
• Maybe monad
Simple Decorator
STL String Complaints
• Making a string is easy
string s{“hello world”};
• Getting its constituent parts is not
vector<strings> words;
boost::split(words, s, boost::is_any_of(“ “));
• Instead I would prefer
auto parts = s.split(“ “);
• It should work with “hello world”
• Maybe some other goodies, e.g.
• Hide size()
• Have length() as a property, not a function
Basic Decorator
class String {
string s;
public:
String(const string &s) : s{ s } { }
};
Implement Split
class String {
string s;
public:
String(const string &s) : s{ s } { }
vector<string> split(string input)
{
vector<string> result;
boost::split(result, s,
boost::is_any_of(input), boost::token_compress_on);
return result;
}
};
Length Proxying
class String {
string s;
public:
String(const string &s) : s{ s } { }
vector<string> split(string input);
size_t get_length() const { return s.length(); }
};
Length Proxying
class String {
string s;
public:
String(const string &s) : s{ s } { }
vector<string> split(string input);
size_t get_length() const { return s.length(); }
// non-standard!
__declspec(property(get = get_length)) size_t length;
};
String Wrapper Usage
String s{ "hello world" };
cout << "string has " <<
s.length << " characters" << endl;
auto words = s.split(" ");
for (auto& word : words)
cout << word << endl;
Decorator Summary
• Aggregate objects
• Can aggregate more than one
• E.g., string and formatting
• Replicate the APIs you want (e.g., length)
• Miss out on the APIs you don’t need
• Add your own features :)
Composite
Scenario
• Neurons connect to other
neurons
• Neuron layers are collections of
neurons
• These two need to be
connectable
Scenario
struct Neuron
{
vector<Neuron*> in, out;
unsigned int id;
Neuron()
{
static int id = 1;
this->id = id++;
}
}
Scenario
struct NeuronLayer : vector<Neuron>
{
NeuronLayer(int count)
{
while (count-- > 0)
emplace_back(Neuron{});
}
}
State Space Explosition
• void connect_to(Neuron& other)
{
out.push_back(&other);
other.in.push_back(this);
}
• Unfortunately, we need 4 functions
• Neuron to Neuron
• Neuron to NeuronLayer
• NeuronLayer to Neuron
• NeuronLayer to NeuronLayer
One Function Solution?
• Simple: treat Neuron as NeuronLayer of size 1
• Not strictly correct
• Does not take into account other concepts (e.g., NeuronRing)
• Better: expose a single Neuron in an iterable fashion
• Other programming languages have interfaces for iteration
• E.g., C# IEnumerable<T>
• yield keyword
• C++ does duck typing
• Expects begin/end pair
• One function solution not possible, but…
Generic Connection Function
struct Neuron
{
...
template <typename T> void connect_to(T& other)
{
for (Neuron& to : other)
connect_to(other);
}
template<> void connect_to<Neuron>(Neuron& other)
{
out.push_back(&other);
other.in.push_back(this);
}
};
Generic Connection Function
struct NeuronLayer : vector<Neuron>
{
…
template <typename T> void connect_to(T& other)
{
for (Neuron& from : *this)
for (Neuron& to : other)
from.connect_to(to);
}
};
How to Iterate on a Single Value?
struct Neuron
{
…
Neuron* begin() { return this; }
Neuron* end() { return this + 1; }
};
API Usage
Neuron n, n2;
NeuronLayer nl, nl2;
n.connect_to(n2);
n.connect_to(nl);
nl.connect_to(n);
nl.connect_to(nl2);
Specification Pattern and the OCP
Open-Closed Principle
• Open for extension, closed for modification
• Bad: jumping into old code to change a stable, functioning system
• Good: making things generic enough to be externally extensible
• Example: product filtering
Scenario
enum class Color { Red, Green, Blue };
enum class Size {Small, Medium, Large };
struct Product
{
std::string name;
Color color;
Size size;
};
Filtering Products
struct ProductFilter
{
typedef std::vector<Product*> Items;
static Items by_color(Items items, Color color)
{
Items result;
for (auto& i : items)
if (i->color == color)
result.push_back(i);
return result;
}
}
Filtering Products
struct ProductFilter
{
typedef std::vector<Product*> Items;
static Items by_color(Items items, Color color) { … }
static Items by_size(Items items, Size size)
{
Items result;
for (auto& i : items)
if (i->size == size)
result.push_back(i);
return result;
}
}
Filtering Products
struct ProductFilter
{
typedef std::vector<Product*> Items;
static Items by_color(Items items, Color color) { … }
static Items by_size(Items items, Size size) { … }
static Items by_color_and_size(Items items, Size size, Color color)
{
Items result;
for (auto& i : items)
if (i->size == size && i->color == color)
result.push_back(i);
return result;
}
}
Violating OCP
• Keep having to rewrite existing code
• Assumes it is even possible (i.e. you have access to source code)
• Not flexible enough (what about other criteria?)
• Filtering by X or Y or X&Y requires 3 functions
• More complexity -> state space explosion
• Specification pattern to the rescue!
ISpecification and IFilter
template <typename T> struct ISpecification
{
virtual bool is_satisfied(T* item) = 0;
};
template <typename T> struct IFilter
{
virtual std::vector<T*> filter(
std::vector<T*> items,
ISpecification<T>& spec) = 0;
};
A Better Filter
struct ProductFilter : IFilter<Product>
{
typedef std::vector<Product*> Products;
Products filter(
Products items,
ISpecification<Product>& spec) override
{
Products result;
for (auto& p : items)
if (spec.is_satisfied(p))
result.push_back(p);
return result;
}
};
Making Specifications
struct ColorSpecification : ISpecification<Product>
{
Color color;
explicit ColorSpecification(const Color color)
: color{color} { }
bool is_satisfied(Product* item) override {
return item->color == color;
}
}; // same for SizeSpecification
Improved Filter Usage
Product apple{ "Apple", Color::Green, Size::Small };
Product tree { "Tree", Color::Green, Size::Large };
Product house{ "House", Color::Blue, Size::Large };
std::vector<Product*> all{ &apple, &tree, &house };
ProductFilter pf;
ColorSpecification green(Color::Green);
auto green_things = pf.filter(all, green);
for (auto& x : green_things)
std::cout << x->name << " is green" << std::endl;
Filtering on 2..N criteria
• How to filter by size and color?
• We don’t want a SizeAndColorSpecification
• State space explosion
• Create combinators
• A specification which combines two other specifications
• E.g., AndSpecification
AndSpecification Combinator
template <typename T> struct AndSpecification : ISpecification<T>
{
ISpecification<T>& first;
ISpecification<T>& second;
AndSpecification(ISpecification<T>& first,
ISpecification<T>& second)
: first{first}, second{second} { }
bool is_satisfied(T* item) override
{
return first.is_satisfied(item) && second.is_satisfied(item);
}
};
Filtering by Size AND Color
ProductFilter pf;
ColorSpecification green(Color::Green);
SizeSpecification big(Size::Large);
AndSpecification<Product> green_and_big{ big, green };
auto big_green_things = pf.filter(all, green_and_big);
for (auto& x : big_green_things)
std::cout << x->name << " is big and green" << std::endl;
Specification Summary
• Simple filtering solution is
• Too difficult to maintain, violates OCP
• Not flexible enough
• Abstract away the specification interface
• bool is_satisfied_by(T something)
• Abstract away the idea of filtering
• Input items + specification  set of filtered items
• Create combinators (e.g., AndSpecification) for combining multiple
specifications
Fluent and Groovy-Style Builders
Scenario
• Consider the construction of structured data
• E.g., an HTML web page
• Stuctured and formalized
• Rules (e.g., P cannot contain another P)
• Can we provide an API for building these?
Building a Simple HTML List
// <ul><li>hello</li><li>world</li></ul>
string words[] = { "hello", "world" };
ostringstream oss;
oss << "<ul>";
for (auto w : words)
oss << " <li>" << w << "</li>";
oss << "</ul>";
printf(oss.str().c_str());
HtmlElement
struct HtmlElement
{
string name;
string text;
vector<HtmlElement> elements;
const size_t indent_size = 2;
string str(int indent = 0) const; // pretty-print
}
Html Builder (non-fluent)
struct HtmlBuilder
{
HtmlElement root;
HtmlBuilder(string root_name) { root.name = root_name; }
void add_child(string child_name, string child_text)
{
HtmlElement e{ child_name, child_text };
root.elements.emplace_back(e);
}
string str() { return root.str(); }
}
Html Builder (non-fluent)
HtmlBuilder builder{"ul"};
builder.add_child("li", "hello")
builder.add_child("li", "world");
cout << builder.str() << endl;
Making It Fluent
struct HtmlBuilder
{
HtmlElement root;
HtmlBuilder(string root_name) { root.name = root_name; }
HtmlBuilder& add_child(string child_name, string child_text)
{
HtmlElement e{ child_name, child_text };
root.elements.emplace_back(e);
return *this;
}
string str() { return root.str(); }
}
Html Builder
HtmlBuilder builder{"ul"};
builder.add_child("li", "hello").add_child("li", "world");
cout << builder.str() << endl;
Associate Builder & Object Being Built
struct HtmlElement
{
static HtmlBuilder build(string root_name)
{
return HtmlBuilder{root_name};
}
};
// usage:
HtmlElement::build("ul")
.add_child_2("li", "hello").add_child_2("li", "world");
Groovy-Style Builders
• Express the structure of the HTML in code
• No visible function calls
• UL {
LI {“hello”},
LI {“world”}
}
• Possible in C++ using uniform initialization
Tag (= HTML Element)
struct Tag
{
string name;
string text;
vector<Tag> children;
vector<pair<string, string>> attributes;
protected:
Tag(const std::string& name, const std::string& text)
: name{name}, text{text} { }
Tag(const std::string& name, const std::vector<Tag>& children)
: name{name}, children{children} { }
}
Paragraph
struct P : Tag
{
explicit P(const std::string& text)
: Tag{"p", text}
{
}
P(std::initializer_list<Tag> children)
: Tag("p", children)
{
}
};
Image
struct IMG : Tag
{
explicit IMG(const std::string& url)
: Tag{"img", ""}
{
attributes.emplace_back(make_pair("src", url));
}
};
Example Usage
std::cout <<
P {
IMG {"http://pokemon.com/pikachu.png"}
}
<< std::endl;
Facet Builders
• An HTML element has different facets
• Attributes, inner elements, CSS definitions, etc.
• A Person class might have different facets
• Address
• Employment information
• Thus, an object might necessitate several builders
Personal/Work Information
class Person
{
// address
std::string street_address, post_code, city;
// employment
std::string company_name, position;
int annual_income = 0;
Person() {} // private!
}
Person Builder (Exposes Facet Builders)
class PersonBuilder
{
Person p;
protected:
Person& person;
explicit PersonBuilder(Person& person)
: person{ person } { }
public:
PersonBuilder() : person{p} { }
operator Person() { return std::move(person); }
// builder facets
PersonAddressBuilder lives();
PersonJobBuilder works();
}
Person Builder (Exposes Facet Builders)
class PersonBuilder
{
Person p;
protected:
Person& person;
explicit PersonBuilder(Person& person)
: person{ person } { }
public:
PersonBuilder() : person{p} { }
operator Person() { return std::move(person); }
// builder facets
PersonAddressBuilder lives();
PersonJobBuilder works();
}
Person Builder Facet Functions
PersonAddressBuilder PersonBuilder::lives()
{
return PersonAddressBuilder{ person };
}
PersonJobBuilder PersonBuilder::works()
{
return PersonJobBuilder{ person };
}
Person Address Builder
class PersonAddressBuilder : public PersonBuilder
{
typedef PersonAddressBuilder Self;
public:
explicit PersonAddressBuilder(Person& person)
: PersonBuilder{ person } { }
Self& at(std::string street_address)
{
person.street_address = street_address;
return *this;
}
Self& with_postcode(std::string post_code);
Self& in(std::string city);
};
Person Job Builder
class PersonJobBuilder : public PersonBuilder
{
typedef PersonJobBuilder Self;
public:
explicit PersonJobBuilder(Person& person)
: PersonBuilder{ person } { }
Self& at(std::string company_name);
Self& as_a(std::string position);
Self& earning(int annual_income);
};
Back to Person
class Person
{
// fields
public:
static PersonBuilder create();
friend class PersonBuilder;
friend class PersonAddressBuilder;
friend class PersonJobBuilder;
};
Final Person Builder Usage
Person p = Person::create()
.lives().at("123 London Road")
.with_postcode("SW1 1GB")
.in("London")
.works().at("PragmaSoft")
.as_a("Consultant")
.earning(10e6);
Maybe Monad
Presence or Absence
• Different ways of expressing absence of value
• Default-initialized value
• string s; // there is no ‘null string’
• Null value
• Address* address;
• Not-yet-initialized smart pointer
• shared_ptr<Address> address
• Idiomatic
• boost::optional
Monads
• Design patterns in functional programming
• First-class function support
• Related concepts
• Algebraic data types
• Pattern matching
• Implementable to some degree in C++
• Functional objects/lambdas
Scenario
struct Address
{
char* house_name; // why not string?
}
struct Person
{
Address* address;
}
Print House Name, If Any
void print_house_name(Person* p)
{
if (p != nullptr &&
p->address != nullptr &&
p->address->house_name != nullptr)
{
cout << p->address->house_name << endl;
}
}
Maybe Monad
• Encapsulate the ‘drill down’ aspect of code
• Construct a Maybe<T> which keeps context
• Context: pointer to evaluated element
• person -> address -> name
• While context is non-null, we drill down
• If context is nullptr, propagation does not happen
• All instrumented using lambdas
Maybe<T>
template <typename T>
struct Maybe {
T* context;
Maybe(T *context) : context(context) { }
}
// but, given Person* p, we cannot make a ‘new Maybe(p)’
template <typename T> Maybe<T> maybe(T* context)
{
return Maybe<T>(context);
}
Usage So Far
void print_house_name(Person* p)
{
maybe(p). // now drill down :)
}
Maybe::With
template <typename T> struct Maybe
{
...
template <typename TFunc>
auto With(TFunc evaluator)
{
if (context == nullptr)
return ??? // cannot return maybe(nullptr) :(
return maybe(evaluator(context));
};
}
What is ???
• In case of failure, we need to return Maybe<U>
• But the type of U should be the return type of evaluator
• But evaluator returns U* and we need U
• Therefore…
• return Maybe<
typename remove_pointer<
decltype(evaluator(context))
>::type>(nullptr);
Maybe::With Finished
template <typename TFunc>
auto With(TFunc evaluator)
{
if (context == nullptr)
return Maybe<typename remove_pointer<
decltype(evaluator(context))>::type>(nullptr);
return maybe(evaluator(context));
};
Usage So Far
void print_house_name(Person* p)
{
maybe(p) // now drill down :)
.With([](auto x) { return x->address; })
.With([](auto x) { return x->house_name; })
. // print here (if context is not null)
}
Maybe::Do
template <typename TFunc>
auto Do(TFunc action)
{
// if context is OK, perform action on it
if (context != nullptr) action(context);
// no context transition, so...
return *this;
}
How It Works
• print_house_name(nullptr)
• Context is null from the outset and continues to be null
• Nothing happens in the entire evaluation chain
• Person p; print_house_name(&p);
• Context is Person, but since Address is null, it becomes null henceforth
• Person p;
p->Address = new Address;
p->Address->HouseName = “My Castle”;
print_house_name(&p);
• Everything works and we get our printout
Maybe Monad Summary
• Example is not specific to nullptr
• E.g., replace pointers with boost::optional
• Default-initialized types are harder
• If s.length() == 0, has it been initialized?
• Monads are difficult due to lack of functional support
• [](auto x) { return f(x); } instead of
x => f(x) as in C#
• No implicits (e.g. Kotlin’s ‘it’)
That’s It!
• Questions?
• Design Patterns in C++ courses on Pluralsight
• dmitrinesteruk@gmail.com
• @dnesteruk

Más contenido relacionado

La actualidad más candente

Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstractionSergey Platonov
 
Oxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resourcesOxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resourcescorehard_by
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)HamletDRC
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchMatteo Battaglio
 
2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - englishJen Yee Hong
 
Let's talks about string operations in C++17
Let's talks about string operations in C++17Let's talks about string operations in C++17
Let's talks about string operations in C++17Bartlomiej Filipek
 
(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operators(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operatorsNico Ludwig
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17LogeekNightUkraine
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_functiontimotheeg
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerAndrey Karpov
 
Basic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersBasic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersJen Yee Hong
 
Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2 「エッジAIモダン計測制御の世界」オ...
Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2  「エッジAIモダン計測制御の世界」オ...Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2  「エッジAIモダン計測制御の世界」オ...
Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2 「エッジAIモダン計測制御の世界」オ...Mr. Vengineer
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Oky Firmansyah
 

La actualidad más candente (20)

Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
 
Oxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resourcesOxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resources
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
 
Vocabulary Types in C++17
Vocabulary Types in C++17Vocabulary Types in C++17
Vocabulary Types in C++17
 
Qt Rest Server
Qt Rest ServerQt Rest Server
Qt Rest Server
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english
 
Let's talks about string operations in C++17
Let's talks about string operations in C++17Let's talks about string operations in C++17
Let's talks about string operations in C++17
 
(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operators(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operators
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
 
Basic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersBasic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmers
 
Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2 「エッジAIモダン計測制御の世界」オ...
Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2  「エッジAIモダン計測制御の世界」オ...Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2  「エッジAIモダン計測制御の世界」オ...
Google Edge TPUで TensorFlow Liteを使った時に 何をやっているのかを妄想してみる 2 「エッジAIモダン計測制御の世界」オ...
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)
 

Destacado

Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляSergey Platonov
 
Использование юнит-тестов для повышения качества разработки
Использование юнит-тестов для повышения качества разработкиИспользование юнит-тестов для повышения качества разработки
Использование юнит-тестов для повышения качества разработкиvictor-yastrebov
 
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...Platonov Sergey
 
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионаловПолухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионаловSergey Platonov
 
Фитнес для вашего кода: как держать его в форме
Фитнес для вашего кода: как держать его в формеФитнес для вашего кода: как держать его в форме
Фитнес для вашего кода: как держать его в формеIlia Shishkov
 
C++ Core Guidelines
C++ Core Guidelines C++ Core Guidelines
C++ Core Guidelines Sergey Zubkov
 
Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017
Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017
Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017Mikhail Matrosov
 
Василий Сорокин, Простой REST сервер на Qt с рефлексией
Василий Сорокин, Простой REST сервер на Qt с рефлексиейВасилий Сорокин, Простой REST сервер на Qt с рефлексией
Василий Сорокин, Простой REST сервер на Qt с рефлексиейSergey Platonov
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Sergey Platonov
 
Александр Фокин, Рефлексия в C++
Александр Фокин, Рефлексия в C++Александр Фокин, Рефлексия в C++
Александр Фокин, Рефлексия в C++Sergey Platonov
 
Григорий Демченко, Универсальный адаптер
Григорий Демченко, Универсальный адаптерГригорий Демченко, Универсальный адаптер
Григорий Демченко, Универсальный адаптерSergey Platonov
 
Сергей Шамбир, Адаптация Promise/A+ для взаимодействия между C++ и Javascript
Сергей Шамбир, Адаптация Promise/A+ для взаимодействия между C++ и JavascriptСергей Шамбир, Адаптация Promise/A+ для взаимодействия между C++ и Javascript
Сергей Шамбир, Адаптация Promise/A+ для взаимодействия между C++ и JavascriptSergey Platonov
 
Догнать и перегнать boost::lexical_cast
Догнать и перегнать boost::lexical_castДогнать и перегнать boost::lexical_cast
Догнать и перегнать boost::lexical_castRoman Orlov
 
Алексей Кутумов, C++ без исключений, часть 3
Алексей Кутумов,  C++ без исключений, часть 3Алексей Кутумов,  C++ без исключений, часть 3
Алексей Кутумов, C++ без исключений, часть 3Platonov Sergey
 
Для чего мы делали свой акторный фреймворк и что из этого вышло?
Для чего мы делали свой акторный фреймворк и что из этого вышло?Для чего мы делали свой акторный фреймворк и что из этого вышло?
Для чего мы делали свой акторный фреймворк и что из этого вышло?Yauheni Akhotnikau
 
Quality assurance of large c++ projects
Quality assurance of large c++ projectsQuality assurance of large c++ projects
Quality assurance of large c++ projectscorehard_by
 

Destacado (18)

Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуля
 
Использование юнит-тестов для повышения качества разработки
Использование юнит-тестов для повышения качества разработкиИспользование юнит-тестов для повышения качества разработки
Использование юнит-тестов для повышения качества разработки
 
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
 
Parallel STL
Parallel STLParallel STL
Parallel STL
 
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионаловПолухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
 
Фитнес для вашего кода: как держать его в форме
Фитнес для вашего кода: как держать его в формеФитнес для вашего кода: как держать его в форме
Фитнес для вашего кода: как держать его в форме
 
C++ Core Guidelines
C++ Core Guidelines C++ Core Guidelines
C++ Core Guidelines
 
Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017
Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017
Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017
 
Василий Сорокин, Простой REST сервер на Qt с рефлексией
Василий Сорокин, Простой REST сервер на Qt с рефлексиейВасилий Сорокин, Простой REST сервер на Qt с рефлексией
Василий Сорокин, Простой REST сервер на Qt с рефлексией
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++
 
Александр Фокин, Рефлексия в C++
Александр Фокин, Рефлексия в C++Александр Фокин, Рефлексия в C++
Александр Фокин, Рефлексия в C++
 
Григорий Демченко, Универсальный адаптер
Григорий Демченко, Универсальный адаптерГригорий Демченко, Универсальный адаптер
Григорий Демченко, Универсальный адаптер
 
Сергей Шамбир, Адаптация Promise/A+ для взаимодействия между C++ и Javascript
Сергей Шамбир, Адаптация Promise/A+ для взаимодействия между C++ и JavascriptСергей Шамбир, Адаптация Promise/A+ для взаимодействия между C++ и Javascript
Сергей Шамбир, Адаптация Promise/A+ для взаимодействия между C++ и Javascript
 
Clang tidy
Clang tidyClang tidy
Clang tidy
 
Догнать и перегнать boost::lexical_cast
Догнать и перегнать boost::lexical_castДогнать и перегнать boost::lexical_cast
Догнать и перегнать boost::lexical_cast
 
Алексей Кутумов, C++ без исключений, часть 3
Алексей Кутумов,  C++ без исключений, часть 3Алексей Кутумов,  C++ без исключений, часть 3
Алексей Кутумов, C++ без исключений, часть 3
 
Для чего мы делали свой акторный фреймворк и что из этого вышло?
Для чего мы делали свой акторный фреймворк и что из этого вышло?Для чего мы делали свой акторный фреймворк и что из этого вышло?
Для чего мы делали свой акторный фреймворк и что из этого вышло?
 
Quality assurance of large c++ projects
Quality assurance of large c++ projectsQuality assurance of large c++ projects
Quality assurance of large c++ projects
 

Similar a Дмитрий Нестерук, Паттерны проектирования в XXI веке

Similar a Дмитрий Нестерук, Паттерны проектирования в XXI веке (20)

Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Return of c++
Return of c++Return of c++
Return of c++
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Modern C++
Modern C++Modern C++
Modern C++
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
Module 1 - Programming Fundamentals.pptx
Module 1 - Programming Fundamentals.pptxModule 1 - Programming Fundamentals.pptx
Module 1 - Programming Fundamentals.pptx
 
C
CC
C
 
c++ ppt.ppt
c++ ppt.pptc++ ppt.ppt
c++ ppt.ppt
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
Java script
Java scriptJava script
Java script
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
C language
C languageC language
C language
 

Más de Sergey Platonov

Лев Казаркин, Удивительные приключения регистров SSE или в поисках одного бага
Лев Казаркин, Удивительные приключения регистров SSE или в поисках одного багаЛев Казаркин, Удивительные приключения регистров SSE или в поисках одного бага
Лев Казаркин, Удивительные приключения регистров SSE или в поисках одного багаSergey Platonov
 
Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Sergey Platonov
 
Павел Филонов, Разделяй и управляй вместе с Conan.io
Павел Филонов, Разделяй и управляй вместе с Conan.ioПавел Филонов, Разделяй и управляй вместе с Conan.io
Павел Филонов, Разделяй и управляй вместе с Conan.ioSergey Platonov
 
Григорий Демченко, Асинхронность и неблокирующая синхронизация
Григорий Демченко, Асинхронность и неблокирующая синхронизацияГригорий Демченко, Асинхронность и неблокирующая синхронизация
Григорий Демченко, Асинхронность и неблокирующая синхронизацияSergey Platonov
 
Антон Полухин. C++17
Антон Полухин. C++17Антон Полухин. C++17
Антон Полухин. C++17Sergey Platonov
 
Павел Беликов, Как избежать ошибок, используя современный C++
Павел Беликов, Как избежать ошибок, используя современный C++Павел Беликов, Как избежать ошибок, используя современный C++
Павел Беликов, Как избежать ошибок, используя современный C++Sergey Platonov
 
Денис Кандров, Пушкова Евгения, QSpec: тестирование графических приложений на Qt
Денис Кандров, Пушкова Евгения, QSpec: тестирование графических приложений на QtДенис Кандров, Пушкова Евгения, QSpec: тестирование графических приложений на Qt
Денис Кандров, Пушкова Евгения, QSpec: тестирование графических приложений на QtSergey Platonov
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereSergey Platonov
 
Александр Тарасенко, Использование python для автоматизации отладки С/C++ код...
Александр Тарасенко, Использование python для автоматизации отладки С/C++ код...Александр Тарасенко, Использование python для автоматизации отладки С/C++ код...
Александр Тарасенко, Использование python для автоматизации отладки С/C++ код...Sergey Platonov
 
Павел Довгалюк, Обратная отладка
Павел Довгалюк, Обратная отладкаПавел Довгалюк, Обратная отладка
Павел Довгалюк, Обратная отладкаSergey Platonov
 
Никита Глушков, К вопросу о реализации кроссплатформенных фреймворков
Никита Глушков, К вопросу о реализации кроссплатформенных фреймворковНикита Глушков, К вопросу о реализации кроссплатформенных фреймворков
Никита Глушков, К вопросу о реализации кроссплатформенных фреймворковSergey Platonov
 
Dori Exterman, Considerations for choosing the parallel computing strategy th...
Dori Exterman, Considerations for choosing the parallel computing strategy th...Dori Exterman, Considerations for choosing the parallel computing strategy th...
Dori Exterman, Considerations for choosing the parallel computing strategy th...Sergey Platonov
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Sergey Platonov
 
Антон Нонко, Классические строки в C++
Антон Нонко, Классические строки в C++Антон Нонко, Классические строки в C++
Антон Нонко, Классические строки в C++Sergey Platonov
 
Михаил Матросов, Повседневный С++: boost и STL
Михаил Матросов, Повседневный С++: boost и STLМихаил Матросов, Повседневный С++: boost и STL
Михаил Матросов, Повседневный С++: boost и STLSergey Platonov
 
Борис Сазонов, RAII потоки и CancellationToken в C++
Борис Сазонов, RAII потоки и CancellationToken в C++Борис Сазонов, RAII потоки и CancellationToken в C++
Борис Сазонов, RAII потоки и CancellationToken в C++Sergey Platonov
 
Илья Шишков, Принципы создания тестируемого кода
Илья Шишков, Принципы создания тестируемого кодаИлья Шишков, Принципы создания тестируемого кода
Илья Шишков, Принципы создания тестируемого кодаSergey Platonov
 
Антон Наумович, Система автоматической крэш-аналитики своими средствами
Антон Наумович, Система автоматической крэш-аналитики своими средствамиАнтон Наумович, Система автоматической крэш-аналитики своими средствами
Антон Наумович, Система автоматической крэш-аналитики своими средствамиSergey Platonov
 
Андрей Карпов, Приватные байки от разработчиков анализатора кода
Андрей Карпов, Приватные байки от разработчиков анализатора кодаАндрей Карпов, Приватные байки от разработчиков анализатора кода
Андрей Карпов, Приватные байки от разработчиков анализатора кодаSergey Platonov
 
Юрий Ефимочев, Компилируемые в реальном времени DSL для С++
Юрий Ефимочев, Компилируемые в реальном времени DSL для С++ Юрий Ефимочев, Компилируемые в реальном времени DSL для С++
Юрий Ефимочев, Компилируемые в реальном времени DSL для С++ Sergey Platonov
 

Más de Sergey Platonov (20)

Лев Казаркин, Удивительные приключения регистров SSE или в поисках одного бага
Лев Казаркин, Удивительные приключения регистров SSE или в поисках одного багаЛев Казаркин, Удивительные приключения регистров SSE или в поисках одного бага
Лев Казаркин, Удивительные приключения регистров SSE или в поисках одного бага
 
Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >
 
Павел Филонов, Разделяй и управляй вместе с Conan.io
Павел Филонов, Разделяй и управляй вместе с Conan.ioПавел Филонов, Разделяй и управляй вместе с Conan.io
Павел Филонов, Разделяй и управляй вместе с Conan.io
 
Григорий Демченко, Асинхронность и неблокирующая синхронизация
Григорий Демченко, Асинхронность и неблокирующая синхронизацияГригорий Демченко, Асинхронность и неблокирующая синхронизация
Григорий Демченко, Асинхронность и неблокирующая синхронизация
 
Антон Полухин. C++17
Антон Полухин. C++17Антон Полухин. C++17
Антон Полухин. C++17
 
Павел Беликов, Как избежать ошибок, используя современный C++
Павел Беликов, Как избежать ошибок, используя современный C++Павел Беликов, Как избежать ошибок, используя современный C++
Павел Беликов, Как избежать ошибок, используя современный C++
 
Денис Кандров, Пушкова Евгения, QSpec: тестирование графических приложений на Qt
Денис Кандров, Пушкова Евгения, QSpec: тестирование графических приложений на QtДенис Кандров, Пушкова Евгения, QSpec: тестирование графических приложений на Qt
Денис Кандров, Пушкова Евгения, QSpec: тестирование графических приложений на Qt
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhere
 
Александр Тарасенко, Использование python для автоматизации отладки С/C++ код...
Александр Тарасенко, Использование python для автоматизации отладки С/C++ код...Александр Тарасенко, Использование python для автоматизации отладки С/C++ код...
Александр Тарасенко, Использование python для автоматизации отладки С/C++ код...
 
Павел Довгалюк, Обратная отладка
Павел Довгалюк, Обратная отладкаПавел Довгалюк, Обратная отладка
Павел Довгалюк, Обратная отладка
 
Никита Глушков, К вопросу о реализации кроссплатформенных фреймворков
Никита Глушков, К вопросу о реализации кроссплатформенных фреймворковНикита Глушков, К вопросу о реализации кроссплатформенных фреймворков
Никита Глушков, К вопросу о реализации кроссплатформенных фреймворков
 
Dori Exterman, Considerations for choosing the parallel computing strategy th...
Dori Exterman, Considerations for choosing the parallel computing strategy th...Dori Exterman, Considerations for choosing the parallel computing strategy th...
Dori Exterman, Considerations for choosing the parallel computing strategy th...
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
 
Антон Нонко, Классические строки в C++
Антон Нонко, Классические строки в C++Антон Нонко, Классические строки в C++
Антон Нонко, Классические строки в C++
 
Михаил Матросов, Повседневный С++: boost и STL
Михаил Матросов, Повседневный С++: boost и STLМихаил Матросов, Повседневный С++: boost и STL
Михаил Матросов, Повседневный С++: boost и STL
 
Борис Сазонов, RAII потоки и CancellationToken в C++
Борис Сазонов, RAII потоки и CancellationToken в C++Борис Сазонов, RAII потоки и CancellationToken в C++
Борис Сазонов, RAII потоки и CancellationToken в C++
 
Илья Шишков, Принципы создания тестируемого кода
Илья Шишков, Принципы создания тестируемого кодаИлья Шишков, Принципы создания тестируемого кода
Илья Шишков, Принципы создания тестируемого кода
 
Антон Наумович, Система автоматической крэш-аналитики своими средствами
Антон Наумович, Система автоматической крэш-аналитики своими средствамиАнтон Наумович, Система автоматической крэш-аналитики своими средствами
Антон Наумович, Система автоматической крэш-аналитики своими средствами
 
Андрей Карпов, Приватные байки от разработчиков анализатора кода
Андрей Карпов, Приватные байки от разработчиков анализатора кодаАндрей Карпов, Приватные байки от разработчиков анализатора кода
Андрей Карпов, Приватные байки от разработчиков анализатора кода
 
Юрий Ефимочев, Компилируемые в реальном времени DSL для С++
Юрий Ефимочев, Компилируемые в реальном времени DSL для С++ Юрий Ефимочев, Компилируемые в реальном времени DSL для С++
Юрий Ефимочев, Компилируемые в реальном времени DSL для С++
 

Último

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyAnusha Are
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 

Último (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 

Дмитрий Нестерук, Паттерны проектирования в XXI веке

  • 1. Design Paterns in the XXI Century Dmitri Nesteruk dmitrinesteruk@gmail.com @dnesteruk
  • 2. What’s In This Talk? • Examples of patterns and approaches in OOP design • Simple decorator • Composite • Specification pattern/OCP • Fluent and Groovy-style builders • Maybe monad
  • 4. STL String Complaints • Making a string is easy string s{“hello world”}; • Getting its constituent parts is not vector<strings> words; boost::split(words, s, boost::is_any_of(“ “)); • Instead I would prefer auto parts = s.split(“ “); • It should work with “hello world” • Maybe some other goodies, e.g. • Hide size() • Have length() as a property, not a function
  • 5. Basic Decorator class String { string s; public: String(const string &s) : s{ s } { } };
  • 6. Implement Split class String { string s; public: String(const string &s) : s{ s } { } vector<string> split(string input) { vector<string> result; boost::split(result, s, boost::is_any_of(input), boost::token_compress_on); return result; } };
  • 7. Length Proxying class String { string s; public: String(const string &s) : s{ s } { } vector<string> split(string input); size_t get_length() const { return s.length(); } };
  • 8. Length Proxying class String { string s; public: String(const string &s) : s{ s } { } vector<string> split(string input); size_t get_length() const { return s.length(); } // non-standard! __declspec(property(get = get_length)) size_t length; };
  • 9. String Wrapper Usage String s{ "hello world" }; cout << "string has " << s.length << " characters" << endl; auto words = s.split(" "); for (auto& word : words) cout << word << endl;
  • 10. Decorator Summary • Aggregate objects • Can aggregate more than one • E.g., string and formatting • Replicate the APIs you want (e.g., length) • Miss out on the APIs you don’t need • Add your own features :)
  • 12. Scenario • Neurons connect to other neurons • Neuron layers are collections of neurons • These two need to be connectable
  • 13. Scenario struct Neuron { vector<Neuron*> in, out; unsigned int id; Neuron() { static int id = 1; this->id = id++; } }
  • 14. Scenario struct NeuronLayer : vector<Neuron> { NeuronLayer(int count) { while (count-- > 0) emplace_back(Neuron{}); } }
  • 15. State Space Explosition • void connect_to(Neuron& other) { out.push_back(&other); other.in.push_back(this); } • Unfortunately, we need 4 functions • Neuron to Neuron • Neuron to NeuronLayer • NeuronLayer to Neuron • NeuronLayer to NeuronLayer
  • 16. One Function Solution? • Simple: treat Neuron as NeuronLayer of size 1 • Not strictly correct • Does not take into account other concepts (e.g., NeuronRing) • Better: expose a single Neuron in an iterable fashion • Other programming languages have interfaces for iteration • E.g., C# IEnumerable<T> • yield keyword • C++ does duck typing • Expects begin/end pair • One function solution not possible, but…
  • 17. Generic Connection Function struct Neuron { ... template <typename T> void connect_to(T& other) { for (Neuron& to : other) connect_to(other); } template<> void connect_to<Neuron>(Neuron& other) { out.push_back(&other); other.in.push_back(this); } };
  • 18. Generic Connection Function struct NeuronLayer : vector<Neuron> { … template <typename T> void connect_to(T& other) { for (Neuron& from : *this) for (Neuron& to : other) from.connect_to(to); } };
  • 19. How to Iterate on a Single Value? struct Neuron { … Neuron* begin() { return this; } Neuron* end() { return this + 1; } };
  • 20. API Usage Neuron n, n2; NeuronLayer nl, nl2; n.connect_to(n2); n.connect_to(nl); nl.connect_to(n); nl.connect_to(nl2);
  • 22. Open-Closed Principle • Open for extension, closed for modification • Bad: jumping into old code to change a stable, functioning system • Good: making things generic enough to be externally extensible • Example: product filtering
  • 23. Scenario enum class Color { Red, Green, Blue }; enum class Size {Small, Medium, Large }; struct Product { std::string name; Color color; Size size; };
  • 24. Filtering Products struct ProductFilter { typedef std::vector<Product*> Items; static Items by_color(Items items, Color color) { Items result; for (auto& i : items) if (i->color == color) result.push_back(i); return result; } }
  • 25. Filtering Products struct ProductFilter { typedef std::vector<Product*> Items; static Items by_color(Items items, Color color) { … } static Items by_size(Items items, Size size) { Items result; for (auto& i : items) if (i->size == size) result.push_back(i); return result; } }
  • 26. Filtering Products struct ProductFilter { typedef std::vector<Product*> Items; static Items by_color(Items items, Color color) { … } static Items by_size(Items items, Size size) { … } static Items by_color_and_size(Items items, Size size, Color color) { Items result; for (auto& i : items) if (i->size == size && i->color == color) result.push_back(i); return result; } }
  • 27. Violating OCP • Keep having to rewrite existing code • Assumes it is even possible (i.e. you have access to source code) • Not flexible enough (what about other criteria?) • Filtering by X or Y or X&Y requires 3 functions • More complexity -> state space explosion • Specification pattern to the rescue!
  • 28. ISpecification and IFilter template <typename T> struct ISpecification { virtual bool is_satisfied(T* item) = 0; }; template <typename T> struct IFilter { virtual std::vector<T*> filter( std::vector<T*> items, ISpecification<T>& spec) = 0; };
  • 29. A Better Filter struct ProductFilter : IFilter<Product> { typedef std::vector<Product*> Products; Products filter( Products items, ISpecification<Product>& spec) override { Products result; for (auto& p : items) if (spec.is_satisfied(p)) result.push_back(p); return result; } };
  • 30. Making Specifications struct ColorSpecification : ISpecification<Product> { Color color; explicit ColorSpecification(const Color color) : color{color} { } bool is_satisfied(Product* item) override { return item->color == color; } }; // same for SizeSpecification
  • 31. Improved Filter Usage Product apple{ "Apple", Color::Green, Size::Small }; Product tree { "Tree", Color::Green, Size::Large }; Product house{ "House", Color::Blue, Size::Large }; std::vector<Product*> all{ &apple, &tree, &house }; ProductFilter pf; ColorSpecification green(Color::Green); auto green_things = pf.filter(all, green); for (auto& x : green_things) std::cout << x->name << " is green" << std::endl;
  • 32. Filtering on 2..N criteria • How to filter by size and color? • We don’t want a SizeAndColorSpecification • State space explosion • Create combinators • A specification which combines two other specifications • E.g., AndSpecification
  • 33. AndSpecification Combinator template <typename T> struct AndSpecification : ISpecification<T> { ISpecification<T>& first; ISpecification<T>& second; AndSpecification(ISpecification<T>& first, ISpecification<T>& second) : first{first}, second{second} { } bool is_satisfied(T* item) override { return first.is_satisfied(item) && second.is_satisfied(item); } };
  • 34. Filtering by Size AND Color ProductFilter pf; ColorSpecification green(Color::Green); SizeSpecification big(Size::Large); AndSpecification<Product> green_and_big{ big, green }; auto big_green_things = pf.filter(all, green_and_big); for (auto& x : big_green_things) std::cout << x->name << " is big and green" << std::endl;
  • 35. Specification Summary • Simple filtering solution is • Too difficult to maintain, violates OCP • Not flexible enough • Abstract away the specification interface • bool is_satisfied_by(T something) • Abstract away the idea of filtering • Input items + specification  set of filtered items • Create combinators (e.g., AndSpecification) for combining multiple specifications
  • 37. Scenario • Consider the construction of structured data • E.g., an HTML web page • Stuctured and formalized • Rules (e.g., P cannot contain another P) • Can we provide an API for building these?
  • 38. Building a Simple HTML List // <ul><li>hello</li><li>world</li></ul> string words[] = { "hello", "world" }; ostringstream oss; oss << "<ul>"; for (auto w : words) oss << " <li>" << w << "</li>"; oss << "</ul>"; printf(oss.str().c_str());
  • 39. HtmlElement struct HtmlElement { string name; string text; vector<HtmlElement> elements; const size_t indent_size = 2; string str(int indent = 0) const; // pretty-print }
  • 40. Html Builder (non-fluent) struct HtmlBuilder { HtmlElement root; HtmlBuilder(string root_name) { root.name = root_name; } void add_child(string child_name, string child_text) { HtmlElement e{ child_name, child_text }; root.elements.emplace_back(e); } string str() { return root.str(); } }
  • 41. Html Builder (non-fluent) HtmlBuilder builder{"ul"}; builder.add_child("li", "hello") builder.add_child("li", "world"); cout << builder.str() << endl;
  • 42. Making It Fluent struct HtmlBuilder { HtmlElement root; HtmlBuilder(string root_name) { root.name = root_name; } HtmlBuilder& add_child(string child_name, string child_text) { HtmlElement e{ child_name, child_text }; root.elements.emplace_back(e); return *this; } string str() { return root.str(); } }
  • 43. Html Builder HtmlBuilder builder{"ul"}; builder.add_child("li", "hello").add_child("li", "world"); cout << builder.str() << endl;
  • 44. Associate Builder & Object Being Built struct HtmlElement { static HtmlBuilder build(string root_name) { return HtmlBuilder{root_name}; } }; // usage: HtmlElement::build("ul") .add_child_2("li", "hello").add_child_2("li", "world");
  • 45. Groovy-Style Builders • Express the structure of the HTML in code • No visible function calls • UL { LI {“hello”}, LI {“world”} } • Possible in C++ using uniform initialization
  • 46. Tag (= HTML Element) struct Tag { string name; string text; vector<Tag> children; vector<pair<string, string>> attributes; protected: Tag(const std::string& name, const std::string& text) : name{name}, text{text} { } Tag(const std::string& name, const std::vector<Tag>& children) : name{name}, children{children} { } }
  • 47. Paragraph struct P : Tag { explicit P(const std::string& text) : Tag{"p", text} { } P(std::initializer_list<Tag> children) : Tag("p", children) { } };
  • 48. Image struct IMG : Tag { explicit IMG(const std::string& url) : Tag{"img", ""} { attributes.emplace_back(make_pair("src", url)); } };
  • 49. Example Usage std::cout << P { IMG {"http://pokemon.com/pikachu.png"} } << std::endl;
  • 50. Facet Builders • An HTML element has different facets • Attributes, inner elements, CSS definitions, etc. • A Person class might have different facets • Address • Employment information • Thus, an object might necessitate several builders
  • 51. Personal/Work Information class Person { // address std::string street_address, post_code, city; // employment std::string company_name, position; int annual_income = 0; Person() {} // private! }
  • 52. Person Builder (Exposes Facet Builders) class PersonBuilder { Person p; protected: Person& person; explicit PersonBuilder(Person& person) : person{ person } { } public: PersonBuilder() : person{p} { } operator Person() { return std::move(person); } // builder facets PersonAddressBuilder lives(); PersonJobBuilder works(); }
  • 53. Person Builder (Exposes Facet Builders) class PersonBuilder { Person p; protected: Person& person; explicit PersonBuilder(Person& person) : person{ person } { } public: PersonBuilder() : person{p} { } operator Person() { return std::move(person); } // builder facets PersonAddressBuilder lives(); PersonJobBuilder works(); }
  • 54. Person Builder Facet Functions PersonAddressBuilder PersonBuilder::lives() { return PersonAddressBuilder{ person }; } PersonJobBuilder PersonBuilder::works() { return PersonJobBuilder{ person }; }
  • 55. Person Address Builder class PersonAddressBuilder : public PersonBuilder { typedef PersonAddressBuilder Self; public: explicit PersonAddressBuilder(Person& person) : PersonBuilder{ person } { } Self& at(std::string street_address) { person.street_address = street_address; return *this; } Self& with_postcode(std::string post_code); Self& in(std::string city); };
  • 56. Person Job Builder class PersonJobBuilder : public PersonBuilder { typedef PersonJobBuilder Self; public: explicit PersonJobBuilder(Person& person) : PersonBuilder{ person } { } Self& at(std::string company_name); Self& as_a(std::string position); Self& earning(int annual_income); };
  • 57. Back to Person class Person { // fields public: static PersonBuilder create(); friend class PersonBuilder; friend class PersonAddressBuilder; friend class PersonJobBuilder; };
  • 58. Final Person Builder Usage Person p = Person::create() .lives().at("123 London Road") .with_postcode("SW1 1GB") .in("London") .works().at("PragmaSoft") .as_a("Consultant") .earning(10e6);
  • 60. Presence or Absence • Different ways of expressing absence of value • Default-initialized value • string s; // there is no ‘null string’ • Null value • Address* address; • Not-yet-initialized smart pointer • shared_ptr<Address> address • Idiomatic • boost::optional
  • 61. Monads • Design patterns in functional programming • First-class function support • Related concepts • Algebraic data types • Pattern matching • Implementable to some degree in C++ • Functional objects/lambdas
  • 62. Scenario struct Address { char* house_name; // why not string? } struct Person { Address* address; }
  • 63. Print House Name, If Any void print_house_name(Person* p) { if (p != nullptr && p->address != nullptr && p->address->house_name != nullptr) { cout << p->address->house_name << endl; } }
  • 64. Maybe Monad • Encapsulate the ‘drill down’ aspect of code • Construct a Maybe<T> which keeps context • Context: pointer to evaluated element • person -> address -> name • While context is non-null, we drill down • If context is nullptr, propagation does not happen • All instrumented using lambdas
  • 65. Maybe<T> template <typename T> struct Maybe { T* context; Maybe(T *context) : context(context) { } } // but, given Person* p, we cannot make a ‘new Maybe(p)’ template <typename T> Maybe<T> maybe(T* context) { return Maybe<T>(context); }
  • 66. Usage So Far void print_house_name(Person* p) { maybe(p). // now drill down :) }
  • 67. Maybe::With template <typename T> struct Maybe { ... template <typename TFunc> auto With(TFunc evaluator) { if (context == nullptr) return ??? // cannot return maybe(nullptr) :( return maybe(evaluator(context)); }; }
  • 68. What is ??? • In case of failure, we need to return Maybe<U> • But the type of U should be the return type of evaluator • But evaluator returns U* and we need U • Therefore… • return Maybe< typename remove_pointer< decltype(evaluator(context)) >::type>(nullptr);
  • 69. Maybe::With Finished template <typename TFunc> auto With(TFunc evaluator) { if (context == nullptr) return Maybe<typename remove_pointer< decltype(evaluator(context))>::type>(nullptr); return maybe(evaluator(context)); };
  • 70. Usage So Far void print_house_name(Person* p) { maybe(p) // now drill down :) .With([](auto x) { return x->address; }) .With([](auto x) { return x->house_name; }) . // print here (if context is not null) }
  • 71. Maybe::Do template <typename TFunc> auto Do(TFunc action) { // if context is OK, perform action on it if (context != nullptr) action(context); // no context transition, so... return *this; }
  • 72. How It Works • print_house_name(nullptr) • Context is null from the outset and continues to be null • Nothing happens in the entire evaluation chain • Person p; print_house_name(&p); • Context is Person, but since Address is null, it becomes null henceforth • Person p; p->Address = new Address; p->Address->HouseName = “My Castle”; print_house_name(&p); • Everything works and we get our printout
  • 73. Maybe Monad Summary • Example is not specific to nullptr • E.g., replace pointers with boost::optional • Default-initialized types are harder • If s.length() == 0, has it been initialized? • Monads are difficult due to lack of functional support • [](auto x) { return f(x); } instead of x => f(x) as in C# • No implicits (e.g. Kotlin’s ‘it’)
  • 74. That’s It! • Questions? • Design Patterns in C++ courses on Pluralsight • dmitrinesteruk@gmail.com • @dnesteruk