100% found this document useful (1 vote)
150 views

Design Patterns in Modern C++: Reusable Approaches for Object-Oriented Software Design 1st Edition Dmitri Nesteruk 2024 scribd download

Approaches

Uploaded by

toullypalkus
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
150 views

Design Patterns in Modern C++: Reusable Approaches for Object-Oriented Software Design 1st Edition Dmitri Nesteruk 2024 scribd download

Approaches

Uploaded by

toullypalkus
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Experience Seamless Full Ebook Downloads for Every Genre at textbookfull.

com

Design Patterns in Modern C++: Reusable Approaches


for Object-Oriented Software Design 1st Edition
Dmitri Nesteruk

https://textbookfull.com/product/design-patterns-in-modern-
c-reusable-approaches-for-object-oriented-software-
design-1st-edition-dmitri-nesteruk/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Design Patterns in .NET Core 3: Reusable Approaches in C#


and F# for Object-Oriented Software Design 2nd Edition
Dmitri Nesteruk
https://textbookfull.com/product/design-patterns-in-net-
core-3-reusable-approaches-in-c-and-f-for-object-oriented-software-
design-2nd-edition-dmitri-nesteruk/
textboxfull.com

Head First Design Patterns: Building Extensible and


Maintainable Object-Oriented Software 2nd Edition Eric
Freeman
https://textbookfull.com/product/head-first-design-patterns-building-
extensible-and-maintainable-object-oriented-software-2nd-edition-eric-
freeman/
textboxfull.com

Mastering PHP design patterns develop robust and reusable


code using a multitude of design patterns for PHP 7 Ali

https://textbookfull.com/product/mastering-php-design-patterns-
develop-robust-and-reusable-code-using-a-multitude-of-design-patterns-
for-php-7-ali/
textboxfull.com

Primary Mathematics Textbook 2B Jennifer Hoerst

https://textbookfull.com/product/primary-mathematics-
textbook-2b-jennifer-hoerst/

textboxfull.com
Systems Analysis and Design An Object Oriented Approach
with UML Dennis

https://textbookfull.com/product/systems-analysis-and-design-an-
object-oriented-approach-with-uml-dennis/

textboxfull.com

Programming In C Object Oriented Features 1st Edition


Laxmisha Rai

https://textbookfull.com/product/programming-in-c-object-oriented-
features-1st-edition-laxmisha-rai/

textboxfull.com

Practical object-oriented design: an agile primer using


Ruby Second Edition Metz

https://textbookfull.com/product/practical-object-oriented-design-an-
agile-primer-using-ruby-second-edition-metz/

textboxfull.com

Making Embedded Systems: Design Patterns for Great


Software, 2nd Edition Elecia White

https://textbookfull.com/product/making-embedded-systems-design-
patterns-for-great-software-2nd-edition-elecia-white/

textboxfull.com

Making Embedded Systems: Design Patterns for Great


Software 2nd Edition Elecia White

https://textbookfull.com/product/making-embedded-systems-design-
patterns-for-great-software-2nd-edition-elecia-white-2/

textboxfull.com
Design Patterns
in Modern C++
Reusable Approaches for
Object-Oriented Software Design

Dmitri Nesteruk
Design Patterns in
Modern C++
Reusable Approaches for
Object-Oriented Software
Design

Dmitri Nesteruk
Design Patterns in Modern C++: Reusable Approaches for Object-Oriented
Software Design
Dmitri Nesteruk
St. Petersburg, Russia

ISBN-13 (pbk): 978-1-4842-3602-4 ISBN-13 (electronic): 978-1-4842-3603-1


https://doi.org/10.1007/978-1-4842-3603-1
Library of Congress Control Number: 2018940774

Copyright © 2018 by Dmitri Nesteruk


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and
images only in an editorial fashion and to the benefit of the trademark owner, with no intention of
infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Steve Anglin
Development Editor: Matthew Moodie
Coordinating Editor: Mark Powers
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233
Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a
California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc
(SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail editorial@apress.com; for reprint, paperback, or
audio rights, please email bookpermissions@springernature.com.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available
to readers on GitHub via the book's product page, located at www.apress.com/9781484236024.
For more detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
Table of Contents
About the Author���������������������������������������������������������������������������������xi
About the Technical Reviewer�����������������������������������������������������������xiii

Chapter 1: Introduction������������������������������������������������������������������������1
Preliminaries���������������������������������������������������������������������������������������������������������2
Who This Book Is For���������������������������������������������������������������������������������������2
On Code Examples�������������������������������������������������������������������������������������������3
On Developer Tools������������������������������������������������������������������������������������������4
Piracy���������������������������������������������������������������������������������������������������������������5
Important Concepts�����������������������������������������������������������������������������������������������5
Curiously Recurring Template Pattern�������������������������������������������������������������5
Mixin Inheritance���������������������������������������������������������������������������������������������6
Properties��������������������������������������������������������������������������������������������������������7
The SOLID Design Principles���������������������������������������������������������������������������������8
Single Responsibility Principle������������������������������������������������������������������������8
Open-Closed Principle�����������������������������������������������������������������������������������11
Liskov Substitution Principle�������������������������������������������������������������������������18
Interface Segregation Principle���������������������������������������������������������������������21
Dependency Inversion Principle��������������������������������������������������������������������24
Time for Patterns!������������������������������������������������������������������������������������������28

iii
Table of Contents

Part I: Creational Patterns���������������������������������������������������������29


Chapter 2: Builder�������������������������������������������������������������������������������33
Scenario��������������������������������������������������������������������������������������������������������������33
Simple Builder�����������������������������������������������������������������������������������������������������35
Fluent Builder������������������������������������������������������������������������������������������������������36
Communicating Intent�����������������������������������������������������������������������������������������37
Groovy-Style Builder�������������������������������������������������������������������������������������������39
Composite Builder�����������������������������������������������������������������������������������������������42
Summary������������������������������������������������������������������������������������������������������������47

Chapter 3: Factories���������������������������������������������������������������������������49
Scenario��������������������������������������������������������������������������������������������������������������49
Factory Method���������������������������������������������������������������������������������������������������51
Factory����������������������������������������������������������������������������������������������������������������52
Inner Factory�������������������������������������������������������������������������������������������������������54
Abstract Factory��������������������������������������������������������������������������������������������������56
Functional Factory����������������������������������������������������������������������������������������������59
Summary������������������������������������������������������������������������������������������������������������60

Chapter 4: Prototype���������������������������������������������������������������������������63
Object Constrution����������������������������������������������������������������������������������������������63
Ordinary Duplication�������������������������������������������������������������������������������������������64
Duplication via Copy Construction����������������������������������������������������������������������65
Serialization��������������������������������������������������������������������������������������������������������68
Prototype Factory������������������������������������������������������������������������������������������������72
Summary������������������������������������������������������������������������������������������������������������74

iv
Table of Contents

Chapter 5: Singleton���������������������������������������������������������������������������75
Singleton as Global Object����������������������������������������������������������������������������������75
Classic Implementation���������������������������������������������������������������������������������������77
Thread Safety������������������������������������������������������������������������������������������������79
The Trouble with Singleton���������������������������������������������������������������������������������80
Singletons and Inversion of Control��������������������������������������������������������������������84
Monostate�����������������������������������������������������������������������������������������������������������85
Summary������������������������������������������������������������������������������������������������������������86

Part II: Structural Patterns��������������������������������������������������������87


Chapter 6: Adapter�����������������������������������������������������������������������������89
Scenario��������������������������������������������������������������������������������������������������������������89
Adapter���������������������������������������������������������������������������������������������������������������91
Adapter Temporaries�������������������������������������������������������������������������������������������94
Summary������������������������������������������������������������������������������������������������������������97

Chapter 7: Bridge��������������������������������������������������������������������������������99
The Pimpl Idiom��������������������������������������������������������������������������������������������������99
Bridge���������������������������������������������������������������������������������������������������������������102
Summary����������������������������������������������������������������������������������������������������������105

Chapter 8: Composite�����������������������������������������������������������������������107
Array Backed Properties�����������������������������������������������������������������������������������108
Grouping Graphic Objects���������������������������������������������������������������������������������111
Neural Networks�����������������������������������������������������������������������������������������������114
Summary����������������������������������������������������������������������������������������������������������118

v
Table of Contents

Chapter 9: Decorator������������������������������������������������������������������������119
Scenario������������������������������������������������������������������������������������������������������������119
Dynamic Decorator�������������������������������������������������������������������������������������������121
Static Decorator������������������������������������������������������������������������������������������������124
Functional Decorator�����������������������������������������������������������������������������������������127
Summary����������������������������������������������������������������������������������������������������������131

Chapter 10: Façade���������������������������������������������������������������������������133


How the Terminal Works�����������������������������������������������������������������������������������134
An Advanced Terminal���������������������������������������������������������������������������������������135
Where’s the Façade?����������������������������������������������������������������������������������������136
Summary����������������������������������������������������������������������������������������������������������138

Chapter 11: Flyweight����������������������������������������������������������������������139


User Names�������������������������������������������������������������������������������������������������������139
Boost.Flyweight������������������������������������������������������������������������������������������������142
String Ranges���������������������������������������������������������������������������������������������������143
Naïve Approach�������������������������������������������������������������������������������������������������143
Flyweight Implementation��������������������������������������������������������������������������������145
Summary����������������������������������������������������������������������������������������������������������147

Chapter 12: Proxy�����������������������������������������������������������������������������149


Smart Pointers��������������������������������������������������������������������������������������������������149
Property Proxy���������������������������������������������������������������������������������������������������150
Virtual Proxy������������������������������������������������������������������������������������������������������152
Communication Proxy���������������������������������������������������������������������������������������154
Summary����������������������������������������������������������������������������������������������������������158

vi
Table of Contents

Part III: Behavioral Patterns����������������������������������������������������159


Chapter 13: Chain of Responsibility�������������������������������������������������161
Scenario������������������������������������������������������������������������������������������������������������161
Pointer Chain�����������������������������������������������������������������������������������������������������162
Broker Chain�����������������������������������������������������������������������������������������������������166
Summary����������������������������������������������������������������������������������������������������������171

Chapter 14: Command����������������������������������������������������������������������173


Scenario������������������������������������������������������������������������������������������������������������173
Implementing the Command Pattern����������������������������������������������������������������175
Undo Operations�����������������������������������������������������������������������������������������������176
Composite Command����������������������������������������������������������������������������������������180
Command Query Separation�����������������������������������������������������������������������������183
Summary����������������������������������������������������������������������������������������������������������187

Chapter 15: Interpreter���������������������������������������������������������������������189


Numeric Expression Evaluator��������������������������������������������������������������������������190
Lexing����������������������������������������������������������������������������������������������������������190
Parsing��������������������������������������������������������������������������������������������������������193
Using Lexer and Parser�������������������������������������������������������������������������������197
Parsing with Boost.Spirit����������������������������������������������������������������������������������197
Abstract Syntax Tree������������������������������������������������������������������������������������198
Parser����������������������������������������������������������������������������������������������������������200
Printer����������������������������������������������������������������������������������������������������������201
Summary����������������������������������������������������������������������������������������������������������202

vii
Table of Contents

Chapter 16: Iterator��������������������������������������������������������������������������205


Iterators in the Standard Library�����������������������������������������������������������������������205
Traversing a Binary Tree������������������������������������������������������������������������������������208
Iteration with Coroutines�����������������������������������������������������������������������������������213
Summary����������������������������������������������������������������������������������������������������������215

Chapter 17: Mediator������������������������������������������������������������������������217


Chat Room��������������������������������������������������������������������������������������������������������217
Mediator with Events����������������������������������������������������������������������������������������223
Summary����������������������������������������������������������������������������������������������������������227

Chapter 18: Memento�����������������������������������������������������������������������229


Bank Account����������������������������������������������������������������������������������������������������229
Undo and Redo��������������������������������������������������������������������������������������������������232
Summary����������������������������������������������������������������������������������������������������������235

Chapter 19: Null Object���������������������������������������������������������������������237


Scenario������������������������������������������������������������������������������������������������������������237
Null Object��������������������������������������������������������������������������������������������������������239
shared_ptr is not a Null Object�������������������������������������������������������������������������239
Design Improvements���������������������������������������������������������������������������������������240
Implicit Null Object��������������������������������������������������������������������������������������������241
Summary����������������������������������������������������������������������������������������������������������242

Chapter 20: Observer������������������������������������������������������������������������243


Property Observers�������������������������������������������������������������������������������������������243
Observer<T>�����������������������������������������������������������������������������������������������������244
Observable<T>�������������������������������������������������������������������������������������������������246
Connecting Observers and Observables�����������������������������������������������������������248
Dependency Problems��������������������������������������������������������������������������������������249

viii
Table of Contents

Unsubscription and Thread Safety��������������������������������������������������������������������250


Reentrancy��������������������������������������������������������������������������������������������������������252
Observer via Boost.Signals2�����������������������������������������������������������������������������255
Summary����������������������������������������������������������������������������������������������������������256

Chapter 21: State������������������������������������������������������������������������������259


State-Driven State Transitions��������������������������������������������������������������������������260
Handmade State Machine���������������������������������������������������������������������������������263
State Machines with Boost.MSM����������������������������������������������������������������������267
Summary����������������������������������������������������������������������������������������������������������272

Chapter 22: Strategy�������������������������������������������������������������������������273


Dynamic Strategy����������������������������������������������������������������������������������������������274
Static Strategy��������������������������������������������������������������������������������������������������278
Summary����������������������������������������������������������������������������������������������������������279

Chapter 23: Template Method�����������������������������������������������������������281


Game Simulation�����������������������������������������������������������������������������������������������281
Summary����������������������������������������������������������������������������������������������������������284

Chapter 24: Visitor����������������������������������������������������������������������������285


Intrusive Visitor�������������������������������������������������������������������������������������������������286
Reflective Printer����������������������������������������������������������������������������������������������288
WTH is Dispatch?����������������������������������������������������������������������������������������������291
Classic Visitor����������������������������������������������������������������������������������������������������293
Implementing an Additional Visitor��������������������������������������������������������������295
Acyclic Visitor����������������������������������������������������������������������������������������������������297
Variants and std::visit����������������������������������������������������������������������������������������299
Summary����������������������������������������������������������������������������������������������������������301

ix
Table of Contents

Part IV: Appendix A: Functional Design Patterns���������������������303


Chapter 25: Maybe Monad����������������������������������������������������������������305

Index�������������������������������������������������������������������������������������������������309

x
About the Author
Dmitri Nesteruk is a quantitative analyst,
developer, course and book author, and an
occasional conference speaker. His professional
interests lie in software development and
integration practices in the areas of computation,
quantitative finance, and algorithmic trading.
His technological interests include C# and
C++ programming as well high-performance
computing using technologies such as CUDA
and FPGAs. He has been a C# MVP since 2009.

xi
About the Technical Reviewer
Massimo Nardone has more than 24 years
of experiences in Security, Web/Mobile
development, Cloud, and IT Architecture. His
true IT passions are Security and Android.
He has been programming and teaching
how to program with Android, Perl, PHP, Java,
VB, Python, C/C++, and MySQL for more than
20 years.
He holds a Master of Science degree in
Computing Science from the University of
Salerno, Italy.
He has worked as a Project Manager, Software Engineer, Research
Engineer, Chief Security Architect, Information Security Manager, PCI/SCADA
Auditor, and Senior Lead IT Security/Cloud/SCADA Architect for many years.
Technical skills include: Security, Android, Cloud, Java, MySQL,
Drupal, Cobol, Perl, Web and Mobile development, MongoDB, D3,
Joomla, Couchbase, C/C++, WebGL, Python, Pro Rails, Django CMS, Jekyll,
Scratch, etc.
He worked as visiting lecturer and supervisor for exercises at the
Networking Laboratory of the Helsinki University of Technology (Aalto
University). He holds four international patents (PKI, SIP, SAML, and Proxy
areas).
He currently works as Chief Information Security Office for Cargotec
Oyj and he is a member of ISACA Finland Chapter Board.
Massimo has reviewed more than 45 IT books for different publishers,
and coauthored Pro JPA 2 in Java EE 8 (Apress, 2018) and Pro Android
Games (Apress, 2015).

xiii
CHAPTER 1

Introduction
The topic of Design Patterns sounds dry, academically constipated and,
in all honesty, done to death in almost every programming language
imaginable—including programming languages such as JavaScript that
aren’t even properly OOP! So why another book on it?
I guess the main reason this book exists is that C++ is great again. After
a long period of stagnation, it’s now evolving, growing, and despite the
fact that it has to contend with backwards C compatibility, good things are
happening, albeit not at the pace we’d all like. (I’m looking at modules,
among other things.)
Now, on to Design Patterns—we shouldn’t forget that the original
Design Patterns book1 was published with examples in C++ and Smalltalk.
Since then, plenty of programming languages have incorporated
design patterns directly into the language: for example, C# directly
incorporated the Observer pattern with its built-in support for events
(and the corresponding event keyword). C++ has not done the same, at
least not on the syntax level. That said, the introduction of types such as
std::function sure made things a lot simpler for many programming
scenarios.

1
 rich Gamma et al., Design Patterns: Elements of Reusable Object-Oriented
E
Software (Boston, MA: Addison Wesley, 1994).

© Dmitri Nesteruk 2018 1


D. Nesteruk, Design Patterns in Modern C++, https://doi.org/10.1007/978-1-4842-3603-1_1
Chapter 1 Introduction

Design Patterns are also a fun investigation of how a problem can


be solved in many different ways, with varying degrees of technical
sophistication and different sorts of trade-offs. Some patterns are more
or less essential and unavoidable, whereas other patterns are more of a
scientific curiosity (but nevertheless will be discussed in this book, since
I’m a completionist).
Readers should be aware that comprehensive solutions to certain
problems (e.g., the Observer pattern) typically result in overengineering,
that is, the creation of structures that are far more complicated than is
necessary for most typical scenarios. While overengineering is a lot of fun
(hey, you get to really solve the problem and impress your coworkers), it’s
often not feasible.

Preliminaries
Who This Book Is For
This book is designed to be a modern-day update to the classic GoF book,
targeting specifically the C++ programming language. I mean, how many
of you are writing Smalltalk out there? Not many; that would be my guess.
The goal of this book is to investigate how we can apply Modern C++
(the latest versions of C++ currently available) to the implementations of
classic design patterns. At the same time, it’s also an attempt to flesh out
any new patterns and approaches that could be useful to C++ developers.
Finally, in some places, this book is quite simply a technology demo for
Modern C++, showcasing how some of its latest features (e.g., coroutines)
make difficult problems a lot easier to solve.

2
Chapter 1 Introduction

On Code Examples


The examples in this book are all suitable for putting into production, but a
few simplifications have been made in order to aid readability:

• Quite often, you’ll find me using struct instead of


class in order to avoid writing the public keyword in
too many places.

• I will avoid the std:: prefix, as it can hurt readability,


especially in places where code density is high. If I’m
using string, you can bet I’m referring to std::string.

• I will avoid adding virtual destructors, whereas in real


life, it might make sense to add them.

• In very few cases I will create and pass parameters by


value to avoid the proliferation of shared_ptr/make_
shared/etc. Smart pointers add another level of
complexity, and their integration into the design
patterns presented in this book is left as an exercise for
the reader.

• I will sometimes omit code elements that would


otherwise be necessary for feature-completing a type
(e.g., move constructors) as those take up too much space.

• There will be plenty of cases where I will omit const


whereas, under normal circumstances, it would
actually make sense. Const-correctness quite often
causes a split and a doubling of the API surface,
something that doesn’t work well in book format.

3
Chapter 1 Introduction

You should be aware that most of the examples leverage Modern C++
(C++11, 14, 17 and beyond) and generally use the latest C++ language
features that are available to developers. For example, you won’t find
many function signatures ending in -> decltype(...) when C++14
lets us automatically infer the return type. None of the examples target
a particular compiler, but if something doesn’t work with your chosen
compiler,2 you’ll need to find workarounds.
At certain points in time, I will be referencing other programming
languages such as C# or Kotlin. It’s sometimes interesting to note how
designers of other languages have implemented a particular feature. C++
is no stranger to borrowing generally available ideas from other languages:
for example, the introduction of auto and type inference on variable
declarations and return types is present in many other languages.

On Developer Tools


The code samples in this book were written to work with modern C++
compilers, be it Clang, GCC, or MSVC. I make the general assumption
that you are using the latest compiler version that is available, and as a
consequence, will use the latest-and-greatest language features that are
available to me. In some cases, the advanced language examples will need
to be downgraded for earlier compilers; in others it might not work out.
As far as developer tools are concerned, this book does not touch
on them specifically, so provided you have an up-to-date compiler, you
should follow the examples just fine: most of them are self-contained .cpp
files. Regardless, I’d like to take this opportunity to remind you that quality
developer tools such as the CLion or ReSharper C++ greatly improve the
development experience. For a tiny amount of money that you invest,
you get a wealth of additional functionality that directly translates to
improvements in coding speed and the quality of the code produced.

2
Intel, I’m looking at you!

4
Chapter 1 Introduction

Piracy
Digital piracy is an inescapeable fact of life. A brand new generation is
growing up right now that has never purchased a movie or a book—even
this book. There’s not much that can be done about this. The only thing
I can say is that if you pirated this book, you might not be reading the latest
version.
The joy of online digital publishing is I get to update the book as new
versions of C++ come out and I do more research. So if you paid for this
book, you’ll get free updates in the future as new versions of the C++
language and the Standard Library are released. If not… oh, well.

Important Concepts
Before we begin, I want to briefly mention some key concepts of the C++
world that are going to be referenced in this book.

Curiously Recurring Template Pattern


Hey, this is a pattern, apparently! I don’t know if it qualifies to be listed
as a separate design pattern, but it’s certainly a pattern of sorts in the
C++ world. Essentially, the idea is simple: an inheritor passes itself as a
template argument to its base class:

1   struct Foo : SomeBase<Foo>


2   {
3     ...
4   }

Now, you might be wondering why one would ever do that? Well,
one reason is to be able to access a typed this pointer inside a base class
implementation.

5
Chapter 1 Introduction

For example, suppose every single inheritor of SomeBase implements a


begin()/end() pair required for iteration. How can you iterate the object
inside a member of SomeBase? Intuition suggests that you cannot, because
SomeBase itself does not provide a begin()/end() interface. But if you use
CRTP, you can actually cast this to a derived class type:

1   template <typename Derived>


2   struct SomeBase
3   {
4     void foo()
5     {
6       for (auto& item : *static_cast<Derived*>(this))
7       {
8         ...
9       }
10     }
11   }

For a concrete example of this approach, check out Chapter 9.

M
 ixin Inheritance
In C++, a class can be defined to inherit from its own template argument,
for example:

1   template <typename T> struct Mixin : T


2   {
3     ...
4   }

This approach is called mixin inheritance and allows hierarchical


composition of types. For example, you can allow Foo<Bar<Baz>> x; to
declare a variable of a type that implements the traits of all three classes,
without having to actually construct a brand new FooBarBaz type.
For a concrete example of this approach, check out Chapter 9.

6
Chapter 1 Introduction

Properties
A property is nothing more than a (typically private) field and a combination
of a getter and a setter. In standard C++, a property looks as follows:

1   class Person
2   {
3     int age;
4   public:
5     int get_age() const { return age; }
6     void set_age(int value) { age = value; }
7   };

Plenty of languages (e.g., C#, Kotlin) internalize the notion of a


property by baking it directly into the programming language. While C++
has not done this (and is unlikely to do so anytime in the future), there is
a nonstandard declaration specifier called property that you can use in
most compilers (MSVC, Clang, Intel):

1   class Person
2   {
3     int age_;
4   public:
5     int get_age() const { return age_; }
6     void set_age(int value) { age_ = value; }
7     __declspec(property(get=get_age, put=set_age)) int age;
8   };

This can be used as follows:

1   Person person;
2   p.age = 20; // calls p.set_age(20)

7
Chapter 1 Introduction

The SOLID Design Principles


SOLID is an acronym which stands for the following design principles (and
their abbreviations):

• Single Responsibility Principle (SRP)

• Open-Closed Principle (OCP)

• Liskov Substitution Principle (LSP)

• Interface Segregation Principle (ISP)

• Dependency Inversion Principle (DIP)

These principles were introduced by Robert C. Martin in the early


2000s—in fact, they are just a selection of five principles out of dozens that
are expressed in Robert’s books and his blog. These five particular topics
permeate the discussion of patterns and software design in general, so
before we dive into design patterns (I know you’re all eager), we’re going to
do a brief recap of what the SOLID principles are all about.

Single Responsibility Principle


Suppose you decide to keep a journal of your most intimate thoughts. The
journal has a title and a number of entries. You could model it as follows:

1   struct Journal
2   {
3     string title;
4     vector<string> entries;
5
6     explicit Journal(const string& title) : title{title} {}
7   };

8
Chapter 1 Introduction

Now, you could add functionality for adding an entry to the journal,
prefixed by the entry’s ordinal number in the journal. This is easy:

1   void Journal::add(const string& entry)


2   {
3     static int count = 1;
4     entries.push_back(boost::lexical_cast<string>(count++)
5       + ": " + entry);
6   }

And the journal is now usable as:

1   Journal j{"Dear Diary"};


2   j.add("I cried today");
3   j.add("I ate a bug");

It makes sense to have this function as part of the Journal class


because adding a journal entry is something the journal actually needs to
do. It is the journal’s responsibility to keep entries, so anything related to
that is fair game.
Now suppose you decide to make the journal persist by saving it in a
file. You add this code to the Journal class:

1   void Journal::save(const string& filename)


2   {
3     ofstream ofs(filename);
4     for (auto& s : entries)
5       ofs << s << endl;
6   }

This approach is problematic. The journal’s responsibility is to keep


journal entries, not to write them to disk. If you add the disk-writing
functionality to Journal and similar classes, any change in the approach
to persistence (say, you decide to write to the cloud instead of disk) would
require lots of tiny changes in each of the affected classes.

9
Chapter 1 Introduction

I want to pause here and make a point: an architecture that leads


you to having to do lots of tiny changes in lost of classes, whether related
(as in a hierarchy) or not, is typically a code smell—an indication that
something’s not quite right. Now, it really depends on the situation: if
you’re renaming a symbol that’s being used in a hundred places, I’d argue
that’s generally OK because ReSharper, CLion, or whatever IDE you use
will actually let you perform a refactoring and have the change propagate
everywhere. But when you need to completely rework an interface… well,
that can be a very painful process!
I therefore state that persistence is a separate concern, one that is
better expressed in a separate class, for example:

1   struct PersistenceManager
2   {
3     static void save(const Journal& j, const string& filename)
4     {
5       ofstream ofs(filename);
6       for (auto& s : j.entries)
7         ofs << s << endl;
8     }
9   };

This is precisely what is meant by Single Responsibility: each class


has only one responsibility, and therefore has only one reason to
change. Journal would need to change only if there’s something more
that needs to be done with respect to storage of entries—for example,
you might want each entry prefixed by a timestamp, so you would
change the add() function to do exactly that. On the other hand, if you
wanted to change the persistence mechanic, this would be changed in
PersistenceManager.

10
Chapter 1 Introduction

An extreme example of an antipattern that violates the SRP is called


a God Object. A God Object is a huge class that tries to handle as many
concerns as possible, becoming a monolithic monstrosity that is very
difficult to work with.
Luckily for us, God Objects are easy to recognize and thanks to
source control systems (just count the number of member functions), the
responsible developer can be quickly identified and adequately punished.

Open-Closed Principle
Suppose we have an (entirely hypothetical) range of products in a
database. Each product has a color and size and is defined as:

1   enum class Color { Red, Green, Blue };


2   enum class Size { Small, Medium, Large };
3
4   struct Product
5   {
6     string name;
7     Color color;
8     Size size;
9   };

Now, we want to provide certain filtering capabilities for a given set of


products. We make a filter similar to the following:

1   struct ProductFilter
2   {
3     typedef vector<Product*> Items;
4   };

Now, to support filtering products by color, we define a member


function to do exactly that:

11
Chapter 1 Introduction

1   ProductFilter::Items ProductFilter::by_color(Items items,


Color color)
2   {
3     Items result;
4     for (auto& i : items)
5       if (i->color == color)
6         result.push_back(i);
7     return result;
8   }

Our current approach of filtering items by color is all well and good.
Our code goes into production but, unfortunately, some time later the boss
comes in and asks us to implement filtering by size, too. So we jump back
into ProductFilter.cpp, add the following code and recompile:

1   ProductFilter::Items ProductFilter::by_color(Items items,


Color color)
2   {
3     Items result;
4     for (auto& i : items)
5       if (i->color == color)
6         result.push_back(i);
7     return result;
8   }

This feels like outright duplication, doesn’t it? Why don’t we just write
a general method that takes a predicate (some function)? Well, one reason
could be that different forms of filtering can be done in different ways: for
example, some record types might be indexed and need to be searched in
a specific way; some data types are amenable to search on a GPU, while
others are not.

12
Chapter 1 Introduction

Our code goes into production but, once again, the boss comes back
and tells us that now there’s a need to search by both color and size. So
what are we to do but add another function?

1   ProductFilter::Items ProductFilter::by_color_and_size(Items
2     items, Size size, Color color)
3   {
4     Items result;
5     for (auto& i : items)
6       if (i->size == size && i->color == color)
7         result.push_back(i);
8     return result;
9   }

What we want, from the preceding scenario, is to enfoce the Open-­Closed


Principle that states that a type is open for extension but closed for
modification. In other words, we want filtering that is extensible
(perhaps in a different compilation unit) without having to modify it (and
recompiling something that already works and may have been shipped to
clients).
How can we achieve it? Well, first of all, we conceptually separate
(SRP!) our filtering process into two parts: a filter (a process which takes
all items and only returns some) and a specification (the definition of a
predicate to apply to a data element).
We can make a very simple definition of a specification interface:

1   template <typename T> struct Specification


2   {
3     virtual bool is_satisfied(T* item) = 0;
4   };

13
Chapter 1 Introduction

In the preceding example, type T is whatever we choose it to be: it can


certainly be a Product, but it can also be something else. This makes the
entire approach reusable.
Next up, we need a way of filtering based on Specification<T>: this is
done by defining, you guessed it, a Filter<T>:

1   template <typename T> struct Filter


2   {
3     virtual vector<T*> filter(
4       vector<T*> items,
5       Specification<T>& spec) = 0;
6   };

Again, all we are doing is specifying the signature for a function called
filter which takes all the items and a specification, and returns all items
that conform to the specification. There is an assumption that the items
are stored as a vector<T*>, but in reality you could pass filter() either
a pair of iterators or some custom-made interface designed specifically
for going through a collection. Regrettably, the C++ language has failed to
standardize the notion of an enumeration or collection, something that
exists in other programming languages (e.g., .NET’s IEnumerable).
Based on the preceding, the implementation of an improved filter is
really simple:

1   struct BetterFilter : Filter<Product>


2   {
3     vector<Product*> filter(
4       vector<Product*> items,
5       Specification<Product>& spec) override
6     {
7       vector<Product*> result;
8       for (auto& p : items)
9         if (spec.is_satisfied(p))

14
Chapter 1 Introduction

10           result.push_back(p);
11       return result;
12     }
13   };

Again, you can think of a Specification<T> that’s being passed in as a


strongly typed equivalent of an std::function that is constrained only to a
certain number of possible filter specifications.
Now, here’s the easy part. To make a color filter, you make a
ColorSpecification:

1   struct ColorSpecification : Specification<Product>


2   {
3     Color color;
4
5     explicit ColorSpecification(const Color color) :
color{color} {}
6
7     bool is_satisfied(Product* item) override {
8       return item->color == color;
9     }
10   };

Armed with this specification, and given a list of products, we can now
filter them as follows:

1   Product apple{ "Apple", Color::Green, Size::Small };


2   Product tree{ "Tree", Color::Green, Size::Large };
3   Product house{ "House", Color::Blue, Size::Large };
4
5   vector<Product*> all{ &apple, &tree, &house };
6
7   BetterFilter bf;

15
Chapter 1 Introduction

8   ColorSpecification green(Color::Green);
9
10   auto green_things = bf.filter(all, green);
11   for (auto& x : green_things)
12     cout << x->name << " is green" << endl;

The preceding gets us “Apple” and “Tree” because they are both green.
Now, the only thing we haven’t implemented so far is searching for size
and color (or, indeed, explained how you would search for size or color,
or mix different criteria). The answer is that you simply make a composite
specification. For example, for the logical AND, you can make it as follows:

1   template <typename T> struct AndSpecification :


Specification<T>
2   {
3     Specification<T>& first;
4     Specification<T>& second;
5
6     AndSpecification(Specification<T>& first,
Specification<T>& second)
7       : first{first}, second{second} {}
8
9     bool is_satisfied(T* item) override
10     {
11       return first.is_satisfied(item) &&
second.is_satisfied(item);
12     }
13   };

Now, you are free to create composite conditions on the basis of


simpler Specifications. Reusing the green specification we made earier,
finding something green and big is now as simple as:

16
Another Random Scribd Document
with Unrelated Content
Æquitas non vaga atque incerta est, sed terminos habet atque
limites præfinitas.
Equity is not vague and uncertain, but has determinate
or prescribed boundaries and limits.

Æquitas non vult res novas atque inusitatas inducere.


Equity does not incline to introduce new and unusual
things.

Æquitas nunquam contravenit legi.


Equity never contravenes the law.

Æquitas nunquam liti ancillatur ubi remedium potest dare.


Equity is never the handmaid to strife, where she can
give a remedy.

Æquitas opitulatur ubi pensationi damni locus est.


Equity assists where there is room for the
compensation of a loss.

Æquitas pars legis Angliæ.


Equity (is) part of the English law.

Æquitas rei oppignoratæ redemptionibus favet.


Equity is favourable for the redemption of a thing given
in pawn.
Æquitas rem ipsam intuetur de forma et circumstantiis minus anxia.
Equity considers the matter itself, less anxious about
the form and circumstances.

Æquitas sequitur legem.


Equity follows or attends the law.

Æquitas supervacua odit.


Equity hates superfluous matters.

Æquitas uxoribus, liberis, creditoribus maxime favet.


Equity is favourable to wives, children, and chiefly to
creditors.

Æquitas veritatis filia, bonitatis et justitiæ soror.


Equity is the daughter of truth, and the sister of
goodness and justice.

Æquitas vult domum quod alteri obsit ex causa æque favorabili esse
ac id quod aufert.
Equity wishes that the house which may be injurious to
another should be in the predicament, equally
favourable to that other, as that which it takes from
him.

Æquitas vult omnibus modis ad veritatem pervenire.


Equity wishes by all means to arrive at truth.

Æquitas vult spoliatos, vel deceptos, vel lapsos ante omnia restituti.
Equity wishes the spoiled, the deceived, and the
ruined, above all things to have restitution.

Æstimatio præteriti delicto ex postremo facto nunquam crescit.


An estimation of the past never increases from the
fault last committed.

Affectio tua nomen imponit operi tuo.


Your affection fixes a character upon your service.

Affectus punitur licet non sequatur effectus.


The inclination is punished although the effect may not
follow.

Affirmanti, non neganti, incubit probatio.


The burden of proving rests upon the person affirming,
not upon him denying.

Affirmativum, negativum implicat.


The affirmative implies the existence of the negative.

Agentes et consentientes pari pœna plectentur.


The principals and accessories should suffer the same
punishment.

Alea et ganea res turpissimæ.


The dice and the brothel are infamous things.
Aliud est possidere, aliud esse in possessione.
It is one thing to possess, and another thing to be in
possession.

Aliud est vendere, aliud vendenti consentire.


It is one thing to sell, and another thing to agree to the
persons selling.

Aliquis non debet esse judex in propria causa; quia non potest esse
judex et pars.
One ought not to be judge in his own cause, because
he cannot be a judge and a party.

Allegans contraria non est audiendus.


A person alleging contradictory things ought not to be
heard.

Allegans suam turpitudinem non est audiendus.


A person alleging his own disgrace is not to be heard.

Allegari non debuit quod probatum non relevat.


That ought not to be alleged, which, when tried is
irrelevant.

Alterius circumventio alii non præbet actionem.


The deceiving of one person does not afford an action
to another.

Alternativa petitio non est audienda.


An alternative petition is not to be heard.

Ambigua autem intentio ita accipienda est, ut res salva actori sit.
An ambiguous answer is so to be understood that the
interest of the pleader may be safe.

Ambigua responsio contra proferentem est accipienda.


An ambiguous answer is to be considered as against
the person who gives it.

Ambiguis casibus semper præsumitur pro rege.


In doubtful cases there is always a presumption in
behalf of the king.

Ambiguitas verborum latens verificatione facti tollitur.


The latent ambiguity of words is removed by the
establishment of the fact.

Ambiguitas verborum latens, verificatione suppletur; nam quod ex


facto oritur ambiguum, verificatione facti tollitur.
The latent ambiguity of words is supplied by their
verification; for the ambiguity which arises from the
fact, is taken away by its being verified.

Ambiguitas verborum patens nulla verificatione excluditur.


The evident ambiguity of words is excluded by no
verification.

Ambiguum pactum contra venditorem interpretandum est.


An ambiguous agreement is to be interpreted against
the seller.

Ambiguum placitum interpretari debet contra proferentem.


An ambiguous order is to be interpreted against the
person uttering it.

Angliæ jura in omni casu libertatis dant favorem.


The laws of England in every case give countenance
to liberty.

Animalia fera, si facta sint mansueta, et ex consuetudine eunt et


redeunt, volant et revolant, ut Cervi, Cygni, &c. eousque nostra sunt;
et ita intelliguntur quamdiu habuerunt animum revertendi.
Wild animals, if they have become tame, and go and
return, fly back and fore, and habitually, as stags and
swans, &c. are so far ours, and are so understood to
be, so long as they are inclined to return to us.

Animi notum vultus detegit.


The countenance is the index of the mind.

Animus hominis est anima scripti.


The mind of man is the soul of his writing.

Aperte impossibilia cum dicuntur non faciunt calumniam.


Impossibilities when they are spoken openly, do not
constitute calumny.
Apices juris non sunt jura.
The extreme points of the law are not the laws.

Applicatio est vita regulæ.


Application is the life of rule.

Arbitrio domini res æstimari debet.


Property ought to be valued at the will of the owner.

Argumenta ignota et obscura ad lucem rationis proferunt et reddunt


splendida.
Arguments bring forward to the light of reason,
unknown and obscure facts, and render them clear.

Argumentum a divisione, est fortissimum in jure.


An argument from division is the strongest in the law.

Argumentum a majori ad minus, negativè, non valet; valet e


converso.
An argument from the greater to the less negatively,
has no weight; contrariwise.

Argumentum a simili valet in lege.


An argument from a like case has weight in law.

Argumentum ab authoritate est fortissimum in lege.


An argument drawn from authority is very strong in law.
Argumentum ab impossibili, plurimum valet in lege.
An argument from an impossibility has very great
weight in law.

Argumentum ab inconvenienti est validum in lege; quia lex non


permittit aliquod inconveniens.
An argument from an incongruous thing is not valid in
law, because the law does not allow any thing
incongruous. [See Transcriber’s Note.]

Arma in armatos sumere jura sinunt.


The laws allow to take arms against the armed.

Assignatus utitur jure auctoris.


An assignee enjoys the privilege of his author.

Aucupia verborum sunt judice indigna.


Hunting curiously for words is unworthy of a judge.

Authoritates philosophorum, medicorum, et poetarum, sunt in causis


allegandæ et tenendæ.
The authorities of philosophers, physicians, and poets,
are to be regarded and held in law.
B.
Baratriam committit qui propter pecuniam justitiam baractat.
He commits barratry who barters justice for money.

Benedicta est expositio quando res redimitur a destructione.


It is a blessed exposure when the thing is redeemed
from destruction.

Beneficium non datum nisi propter officium.


A favour is not granted, unless on account of service.

Beneficium non datur nisi officii causa.


A benefice is not granted but for the sake of duty.

Beneficium clericale omnibus patet ubi pœna capitalis statuto


inducitur, nisi ex expresso tollatur.
The benefit of the clergy is open to all, when capital
punishment is inflicted by the statute, unless it be
taken away expressly.

Beneficium principis debet esse mansurum.


The kindness of a prince ought to be permanent.

Benigne faciendæ sunt interpretationes chartarum, ut res magis


valeat quam pereat.
The meaning or interpretation of writs is to be
favourably taken, that the matter may rather succeed
than perish.

Benigne faciendæ sunt interpretationes, ut res magis valeat quam


pereat, et ut voletur repugnantia et supervacua.
Interpretations are to be made favourably, that the
thing may succeed rather than perish; and what is
repugnant and superfluous may be avoided.

Benigne faciendæ sunt interpretationes propter simplicitatem


laicorum, ut res magis valeat quam pereat.
Interpretations are to be favourably given of the
simplicity of the laity, that the affair may rather prosper
than perish.

Benignior sententia in verbis generalibus seu dubiis, est præferenda.


The more favourable opinion in general or doubtful
words is to be preferred.

Benignius leges interpretandæ sunt, quo voluntas earum


conservetur.
The laws are to be more favourably explained that their
will or intention may be preserved.

Bis idem exegi bona fides non patitur; et in satisfactionibus, non


permittitur amplius fieri quam semel factum est.
Honesty does not suffer the same thing to be exacted
twice; and in satisfaction it is not granted that more be
done than hath been once done.
Bona fides non patitur, ut bis idem exigatur.
Honesty does not permit the same thing to be exacted
twice.

Bonæ fidei possessor, in id tantum quod ad se pervenerit, tenetur.


A bona fide possessor is bound only with respect to
that which has come to him.

Boni judicis est ampliare jurisdictionem.


It is the property of a good judge to enlarge his
jurisdiction.

Boni judicis est ampliare justitiam.


It is the property of a good judge to enlarge or extend
justice.

Boni judicis est causas litium dirimere.


It is the property of a good judge to put an end to the
causes of litigation.

Boni judicis est judicium sine dilatione mandare executioni.


It is the property of a good judge to give a mandate for
execution without delay.

Boni judicis est lites dirimere, ne lis ex lite oritur; et interest


reipublicæ ut sint fines litium.
It is the property of a good judge to put an end to law
suits, lest law suit should arise out of law suit; and it is
the interest of the state that there be limits to law suits.
Bonus judex secundum æquum et bonum judicat, et æquitatem
stricto juri præfert.
A good judge decides according to what is just and
good; and prefers equity to strict law.

Bonum defendentis ex integra causa, malum ex quolibet defectu.


Good is the result of a person defending from an entire
cause: evil results from one defending from any defect.

Bonum necessarium extra terminos necessitatis non est bonum.


A necessary good beyond the limits of necessity, is no
good.
C.
Carcer ad homines custodiendos, non ad puniendos, dari debet.
A prison ought to be assigned for keeping men, not for
punishing them.

Carcer non supplicii causa sed custodiæ constitutus.


A prison is ordained not for the sake of punishment,
but for ward.

Casus fortuitus non est sperandus, et nemo tenetur divinare.


A fortuitous case is not to be calculated upon, and
nobody is bound to conjecture what may happen.

Casus omissus pro omisso habendus est.


A case omitted is to be considered as omitted.

Casus omissus et oblivioni datus, depositioni communis juris


relinquitur.
A case omitted and consigned to oblivion is left to the
disposal of common law.

Catella juste possessa amitti non possunt.


A little whelp, (perhaps cattle), lawfully possessed,
cannot be lost. [See Transcriber’s Note.]
Catalla reputantur inter minima in lege.
Chattels are considered as among the least things, in
law.

Causa et origo est materia negotii.


Cause and origin are the subject matters of business.

Causa publica vicarium non recipit.


A public cause does not admit of a substitute.

Causa vaga et incerta, non est causa rationabilis.


A vague and uncertain cause is not a reasonable
cause.

Cautionis in re plus est quam in persona.


There is more security in the thing than in a person.

Caveat emptor; caveat venditor.


Let the purchaser beware—let the seller beware.

Caveat emptor; qui ignorare non debuit quod jus alienum emit.
Let the purchaser take care; who ought not to be
ignorant what right of another he purchases.

Certa debet esse intentio et narratio, et certum fundamentum, et


certa res quæ deducitur in judicium.
The design and narration ought to be certain, and the
foundation certain, and the matter certain, which is
brought into court to be tried.

Certum est quod certum reddi potest.


What can be rendered certain is certain.

Cessa regnare si non vis judicare.


Cease to reign if there be no power to judge.

Cessante causa, cessat effectus.


The cause ceasing, the effect ceases.

Cessante ratione legis, cessat ipsa lex.


The reason of a law discontinuing, the law itself
discontinues.

Charta ejus quæ sub potestate viri sit in lege nulla.


The writing of that woman who is under the power of
her husband has no legal weight—is void in law.

Chirographum apud debitorem repertum præsumitur solutum.


A bill found in the possession of a debtor, is presumed
to be paid.

Certa res oportet in judicium deducatur.


A certain matter is necessary sometimes to be brought
into court for trial.

Clam delinquentes magis puniuntur quam palam.


Clandestine transactions are more severely punished
than those openly committed.

Clausula generalis de residuo non ea complectitur quæ non ejusdem


sint generis cum iis quæ speciatim dicta fuerant.
A general clause of reservation does not comprehend
those things which may not be of the same kind with
those which have been specially expressed.

Clausula generalis non refertur ad expressa.


A general clause does not refer to things mentioned.

Clausula vel dispositio inutilis per præsumptionem remotam vel


causam ex post facto non fulcitur.
An unnecessary clause, or disposition, is not
supported by a remote inference, or an ex post facto
cause.

Clausulæ inconsuetæ semper inducunt suspicionem.


Uncustomary clauses always induce suspicion.

Clerici non ponantur in officio seculari.


The clergy cannot be placed in a secular office.

Collegium seu corpus corporatum nisi regiis constitutionibus non


potest existere.
A college or incorporated body, cannot exist unless by
royal authority.
Commercium jure gentium commune esse debet, et non in
monopolium et privatum paucorum quæstum convertendum.
Commerce by the law of nations ought to be common,
and not to be converted into a monopoly, and the
private gain of a few.

Commodum ex injuria sua nemo habere debet.


Nobody ought to derive advantage from his injurious
behaviour.

Communis error facit jus.


A common error makes law necessary.

Communiter unum officium est excusatio alterius.


One duty commonly is the excuse for the non
performance of another.

Concessio versus concedentem latam interpretationem habere


debeat.
A grant made to another person granting, should have
a wide interpretation.

Condictio dicitur, cum quid in casum incertum, qui potest tendere ad


esse aut non esse, confertur.
The appointment of an action for a certain day, is said
to take place, when any thing in an uncertain case
happens, which may have a tendency to be or not to
be. [See Transcriber’s Note.]
Condictio rei furtivæ, quia rei habet persecutionem, hæredem
quoque furis obligat.
The appointment of an action on a certain day, relating
to stolen goods, as it implies the production of these
stolen goods, binds the heir of the thief also.

Condictio præcedens adimpleri debet priusquam sequatur effectus.


The appointment of an action preceding, ought to take
place before any effect can follow. [See Transcriber’s
Note.]

Condictio ad liberum tenementum auferendum non nisi ex facto


placitari debet.
An argument for taking away a free tenure, ought not
to be pleaded, except from the deed.

Conditio beneficialis quæ statum construit, benigne, secundum


verborum intentionem est interpretanda; odiosa, autem, quæ statum
destruit, stricte, secundum verborum proprietatem, accipienda.
A beneficial agreement which confirms one state, is to
be interpreted favourably, according to the intention of
the words; but an odious agreement, which destroys
one state, is to be understood strictly, according to the
exact meaning of the words.

Conditio ex parte extincta ex toto extinguitur.


An agreement extinguished in part, is wholly
extinguished.

Conditio liberum tenementum cassans non per nuda verba sine


charta valebit.
An agreement making void a free tenement, will have
no weight by bare words without writing.

Conditio neminem juvabit nisi qui pars fuerit aut privus.


An agreement shall avail no one, unless he shall have
been a party, or privy to it.

Conditio partim extincta in omnibus extinguitur.


An agreement extinguished in any of its parts, is
extinguished in them all.

Conditiones præcedentes ad normam legis severe exigendæ; aliter


de subsequentibus ubi æquitati licet damnum rei infectæ pensari.
Preceding agreements must be rigorously exacted
according to the rule of the law; it is otherwise
concerning subsequent agreements, where equity is
allowed to make up for the loss incurred by the failure.

Conditiones præcedentes stricte interpretandæ, sed non ita de


subsequentibus.
Preceding agreements are to be strictly interpreted; but
not so concerning subsequent ones.

Conditiones quælibet odiosæ; maxime autem contra matrimonium et


commercium.
Some agreements are odious, but chiefly those against
matrimony and commerce.

Confessio facta in judicio, omni probatione major est.


Confession made in a trial is stronger than all proof.
Confessus in judicio pro judicato habetur, et quodammodo sua
sententia damnatur.
A person who confesses on trial, is considered as
judged; and in some measure is condemned on his
own admission.

Confirmare nemo potest priusquam jus ei accederit.


Nobody can confirm before the right fall to him.

Confirmare est id quod prius infirmum fuit, firmare vel firmum facere.
To confirm is to strengthen, or make strong, that which
before was weak.

Confirmat usum qui tollit abusum.


He confirms the use who takes away the abuse.

Confirmatio est nulla ubi donum præcedens est invalidum.


There is no confirmation where the preceding gift is
invalid.

Confirmatio est possessionis jure defective per eos quorum jus est
ratihabitio.
The confirmation of a possession defective in law, is a
ratification by means of those whose right it is.

Confirmatio omnes supplet defectus, licet id quod actum est ab initio


non valuit.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like