You are on page 1of 13

Clean C++

Sustainable Software Development Patterns


and Best Practices with C++ 17

Stephan Roth
Clean C++: Sustainable Software Development Patterns and Best Practices with C++ 17
Stephan Roth
Bad Schwartau, Schleswig-Holstein, Germany
ISBN-13 (pbk): 978-1-4842-2792-3 ISBN-13 (electronic): 978-1-4842-2793-0
DOI 10.1007/978-1-4842-2793-0
Library of Congress Control Number: 2017955209
Copyright © 2017 by Stephan Roth
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.
Cover image by Freepik (www.freepik.com)
Managing Director: Welmoed Spahr
Editorial Director: Todd Green
Acquisitions Editor: Steve Anglin
Development Editor: Matthew Moodie
Technical Reviewer: Marc Gregoire
Coordinating Editor: Mark Powers
Copy Editor: Karen Jameson
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 rights@apress.com, or visit http://www.apress.com/
rights-permissions.
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/9781484227923. For more
detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
To Caroline and Maximilian: my beloved and marvelous family.
Contents at a Glance

About the Author��������������������������������������������������������������������������������������������������� xiii


About the Technical Reviewer���������������������������������������������������������������������������������xv
Acknowledgments�������������������������������������������������������������������������������������������������xvii


■Chapter 1: Introduction����������������������������������������������������������������������������������������� 1

■Chapter 2: Build a Safety Net�������������������������������������������������������������������������������� 9

■Chapter 3: Be Principled�������������������������������������������������������������������������������������� 27

■Chapter 4: Basics of Clean C++��������������������������������������������������������������������������� 41

■Chapter 5: Advanced Concepts of Modern C++��������������������������������������������������� 85

■Chapter 6: Object Orientation���������������������������������������������������������������������������� 133

■Chapter 7: Functional Programming����������������������������������������������������������������� 167

■Chapter 8: Test-Driven Development����������������������������������������������������������������� 191

■Chapter 9: Design Patterns and Idioms������������������������������������������������������������� 217

■Appendix A: Small UML Guide��������������������������������������������������������������������������� 273

■Bibliography������������������������������������������������������������������������������������������������������ 285

Index��������������������������������������������������������������������������������������������������������������������� 287

v
Contents

About the Author��������������������������������������������������������������������������������������������������� xiii


About the Technical Reviewer���������������������������������������������������������������������������������xv
Acknowledgments�������������������������������������������������������������������������������������������������xvii


■Chapter 1: Introduction����������������������������������������������������������������������������������������� 1
Software Entropy�������������������������������������������������������������������������������������������������������������� 2
Clean Code����������������������������������������������������������������������������������������������������������������������� 3
Why C++?������������������������������������������������������������������������������������������������������������������������ 4
C++11 – The Beginning of a New Era������������������������������������������������������������������������������ 4
Who This Book Is For�������������������������������������������������������������������������������������������������������� 5
Conventions Used in This Book���������������������������������������������������������������������������������������� 5
Sidebars������������������������������������������������������������������������������������������������������������������������������������������������� 5
Notes, Tips, and Warnings���������������������������������������������������������������������������������������������������������������������� 6
Code Samples����������������������������������������������������������������������������������������������������������������������������������������� 6

Companion Website and Source Code Repository����������������������������������������������������������� 7


UML Diagrams������������������������������������������������������������������������������������������������������������������ 7

■Chapter 2: Build a Safety Net�������������������������������������������������������������������������������� 9
The Need for Testing�������������������������������������������������������������������������������������������������������� 9
Introduction into Testing������������������������������������������������������������������������������������������������� 11
Unit Tests������������������������������������������������������������������������������������������������������������������������ 13
What about QA?�������������������������������������������������������������������������������������������������������������� 14
Rules for Good Unit Tests����������������������������������������������������������������������������������������������� 15
Test Code Quality���������������������������������������������������������������������������������������������������������������������������������� 15
Unit Test Naming����������������������������������������������������������������������������������������������������������������������������������� 15
vii
■ Contents

Unit Test Independence������������������������������������������������������������������������������������������������������������������������ 16


One Assertion per Test�������������������������������������������������������������������������������������������������������������������������� 17
Independent Initialization of Unit Test Environments���������������������������������������������������������������������������� 18
Exclude Getters and Setters����������������������������������������������������������������������������������������������������������������� 18
Exclude Third-Party Code��������������������������������������������������������������������������������������������������������������������� 18
Exclude External Systems�������������������������������������������������������������������������������������������������������������������� 19
And What Do We Do with the Database?���������������������������������������������������������������������������������������������� 19
Don’t Mix Test Code with Production Code������������������������������������������������������������������������������������������� 19
Tests Must Run Fast����������������������������������������������������������������������������������������������������������������������������� 22
Test Doubles (Fake Objects)����������������������������������������������������������������������������������������������������������������� 22


■Chapter 3: Be Principled�������������������������������������������������������������������������������������� 27
What Is a Principle?�������������������������������������������������������������������������������������������������������� 27
KISS�������������������������������������������������������������������������������������������������������������������������������� 28
YAGNI������������������������������������������������������������������������������������������������������������������������������ 28
DRY��������������������������������������������������������������������������������������������������������������������������������� 29
Information Hiding���������������������������������������������������������������������������������������������������������� 29
Strong Cohesion������������������������������������������������������������������������������������������������������������� 32
Loose Coupling��������������������������������������������������������������������������������������������������������������� 35
Be Careful with Optimizations���������������������������������������������������������������������������������������� 39
Principle of Least Astonishment (PLA)���������������������������������������������������������������������������� 39
The Boy Scout Rule�������������������������������������������������������������������������������������������������������� 39

■Chapter 4: Basics of Clean C++��������������������������������������������������������������������������� 41
Good Names������������������������������������������������������������������������������������������������������������������� 41
Names Should Be Self-Explanatory������������������������������������������������������������������������������������������������������ 43
Use Names from the Domain���������������������������������������������������������������������������������������������������������������� 44
Choose Names at an Appropriate Level of Abstraction������������������������������������������������������������������������� 45
Avoid Redundancy When Choosing a Name����������������������������������������������������������������������������������������� 46
Avoid Cryptic Abbreviations������������������������������������������������������������������������������������������������������������������ 46
Avoid Hungarian Notation and Prefixes������������������������������������������������������������������������������������������������ 47
Avoid Using the Same Name for Different Purposes���������������������������������������������������������������������������� 48

viii
■ Contents

Comments���������������������������������������������������������������������������������������������������������������������� 48
Let the Code Tell a Story����������������������������������������������������������������������������������������������������������������������� 49
Do Not Comment Obvious Things��������������������������������������������������������������������������������������������������������� 49
Don’t Disable Code with Comments����������������������������������������������������������������������������������������������������� 50
Don’t Write Block Comments���������������������������������������������������������������������������������������������������������������� 50
The Rare Cases Where Comments Are Useful�������������������������������������������������������������������������������������� 53

Functions������������������������������������������������������������������������������������������������������������������������ 56
One Thing, No More!����������������������������������������������������������������������������������������������������������������������������� 58
Let Them Be Small�������������������������������������������������������������������������������������������������������������������������������� 59
Function Naming���������������������������������������������������������������������������������������������������������������������������������� 60
Use Intention-Revealing Names����������������������������������������������������������������������������������������������������������� 61
Arguments and Return Values�������������������������������������������������������������������������������������������������������������� 61

About Old C-style in C++ Projects��������������������������������������������������������������������������������� 72


Prefer C++ Strings and Streams over Old C-Style char*���������������������������������������������������������������������� 72
Avoid Using printf(), sprintf(), gets(), etc.���������������������������������������������������������������������������������������������� 74
Prefer Standard Library Containers over Simple C-style Arrays����������������������������������������������������������� 77
Use C++ casts Instead of Old C-Style Casts���������������������������������������������������������������������������������������� 80
Avoid Macros���������������������������������������������������������������������������������������������������������������������������������������� 82


■Chapter 5: Advanced Concepts of Modern C++��������������������������������������������������� 85
Managing Resources������������������������������������������������������������������������������������������������������ 85
Resource Acquisition Is Initialization (RAII)������������������������������������������������������������������������������������������� 87
Smart Pointers�������������������������������������������������������������������������������������������������������������������������������������� 87
Avoid Explicit New and Delete�������������������������������������������������������������������������������������������������������������� 93
Managing Proprietary Resources��������������������������������������������������������������������������������������������������������� 93

We Like to Move It���������������������������������������������������������������������������������������������������������� 94


What Are Move Semantics?������������������������������������������������������������������������������������������������������������������ 95
The Matter with Those lvalues and rvalues������������������������������������������������������������������������������������������ 96
rvalue References��������������������������������������������������������������������������������������������������������������������������������� 97
Don’t Enforce Move Everywhere���������������������������������������������������������������������������������������������������������� 98
The Rule of Zero����������������������������������������������������������������������������������������������������������������������������������� 99

ix
■ Contents

The Compiler Is Your Colleague������������������������������������������������������������������������������������ 102


Automatic Type Deduction������������������������������������������������������������������������������������������������������������������ 103
Computations during Compile Time���������������������������������������������������������������������������������������������������� 106
Variable Templates����������������������������������������������������������������������������������������������������������������������������� 108

Don’t Allow Undefined Behavior����������������������������������������������������������������������������������� 109


Type-Rich Programming����������������������������������������������������������������������������������������������� 110
Know Your Libraries����������������������������������������������������������������������������������������������������� 116
Take Advantage of <algorithm>��������������������������������������������������������������������������������������������������������� 117
Take Advantage of Boost�������������������������������������������������������������������������������������������������������������������� 122
More Libraries That You Should Know About�������������������������������������������������������������������������������������� 123

Proper Exception and Error Handling��������������������������������������������������������������������������� 123


Prevention Is Better Than Aftercare���������������������������������������������������������������������������������������������������� 124
An Exception Is an Exception – Literally!�������������������������������������������������������������������������������������������� 128
If You Can’t Recover, Get Out Quickly�������������������������������������������������������������������������������������������������� 129
Define User-Specific Exception Types������������������������������������������������������������������������������������������������ 129
Throw by Value, Catch by const Reference����������������������������������������������������������������������������������������� 131
Pay Attention to the Correct Order of Catch-Clauses�������������������������������������������������������������������������� 131


■Chapter 6: Object Orientation���������������������������������������������������������������������������� 133
Object-Oriented Thinking��������������������������������������������������������������������������������������������� 133
Abstraction – the Key to Master Complexity���������������������������������������������������������������� 135
Principles for Good Class Design��������������������������������������������������������������������������������� 135
Keep Classes Small���������������������������������������������������������������������������������������������������������������������������� 136
Single Responsibility Principle (SRP)�������������������������������������������������������������������������������������������������� 137
Open-Closed Principle (OCP)�������������������������������������������������������������������������������������������������������������� 137
Liskov Substitution Principle (LSP)����������������������������������������������������������������������������������������������������� 138
Interface Segregation Principle (ISP)�������������������������������������������������������������������������������������������������� 149
Acyclic Dependency Principle������������������������������������������������������������������������������������������������������������� 150
Dependency Inversion Principle (DIP)������������������������������������������������������������������������������������������������� 153
Don’t Talk to Strangers (Law of Demeter)������������������������������������������������������������������������������������������� 158
Avoid Anemic Classes������������������������������������������������������������������������������������������������������������������������� 163

x
■ Contents

Tell, Don’t Ask!������������������������������������������������������������������������������������������������������������������������������������ 163


Avoid Static Class Members��������������������������������������������������������������������������������������������������������������� 165


■Chapter 7: Functional Programming����������������������������������������������������������������� 167
What Is Functional Programming?������������������������������������������������������������������������������� 168
What Is a Function?���������������������������������������������������������������������������������������������������������������������������� 169
Pure vs. Impure Functions������������������������������������������������������������������������������������������������������������������ 170

Functional Programming in Modern C++��������������������������������������������������������������������� 171


Functional Programming with C++ Templates����������������������������������������������������������������������������������� 171
Function-Like Objects (Functors)�������������������������������������������������������������������������������������������������������� 173
Binders and Function Wrappers��������������������������������������������������������������������������������������������������������� 179
Lambda Expressions��������������������������������������������������������������������������������������������������������������������������� 181
Generic Lambda Expressions (C++14)����������������������������������������������������������������������������������������������� 183

Higher-Order Functions������������������������������������������������������������������������������������������������ 184


Map, Filter, and Reduce���������������������������������������������������������������������������������������������������������������������� 185

Clean Code in Functional Programming����������������������������������������������������������������������� 189



■Chapter 8: Test-Driven Development����������������������������������������������������������������� 191
The Drawbacks of Plain Old Unit Testing (POUT)���������������������������������������������������������� 192
Test-Driven Development as a Game Changer������������������������������������������������������������� 193
The Workflow of TDD�������������������������������������������������������������������������������������������������������������������������� 193
TDD by Example: The Roman Numerals Code Kata���������������������������������������������������������������������������� 196
The Advantages of TDD������������������������������������������������������������������������������������������������ 213
When We Should Not Use TDD�������������������������������������������������������������������������������������� 215

■Chapter 9: Design Patterns and Idioms������������������������������������������������������������� 217
Design Principles vs. Design Patterns�������������������������������������������������������������������������� 217
Some Patterns, and When to Use Them����������������������������������������������������������������������� 218
Dependency Injection (DI)������������������������������������������������������������������������������������������������������������������� 218
Adapter����������������������������������������������������������������������������������������������������������������������������������������������� 230
Strategy���������������������������������������������������������������������������������������������������������������������������������������������� 231
Command������������������������������������������������������������������������������������������������������������������������������������������� 235
Command Processor�������������������������������������������������������������������������������������������������������������������������� 239

xi
■ Contents

Composite������������������������������������������������������������������������������������������������������������������������������������������� 242
Observer��������������������������������������������������������������������������������������������������������������������������������������������� 245
Factories��������������������������������������������������������������������������������������������������������������������������������������������� 250
Facade������������������������������������������������������������������������������������������������������������������������������������������������ 253
Money Class��������������������������������������������������������������������������������������������������������������������������������������� 254
Special Case Object (Null Object)������������������������������������������������������������������������������������������������������� 257

What Is an Idiom?��������������������������������������������������������������������������������������������������������� 260


Some Useful C++ Idioms�������������������������������������������������������������������������������������������������������������������� 261


■Appendix A: Small UML Guide��������������������������������������������������������������������������� 273
Class Diagrams������������������������������������������������������������������������������������������������������������ 273
Class��������������������������������������������������������������������������������������������������������������������������������������������������� 273
Interface��������������������������������������������������������������������������������������������������������������������������������������������� 275
Association����������������������������������������������������������������������������������������������������������������������������������������� 278
Generalization������������������������������������������������������������������������������������������������������������������������������������� 280
Dependency���������������������������������������������������������������������������������������������������������������������������������������� 281

Components����������������������������������������������������������������������������������������������������������������� 282
Stereotypes������������������������������������������������������������������������������������������������������������������ 283

■Bibliography������������������������������������������������������������������������������������������������������ 285

Index��������������������������������������������������������������������������������������������������������������������� 287

xii
About the Author

Stephan Roth, born on May 15, 1968, is a passionate coach, consultant,


and trainer for Systems and Software Engineering with German
consultancy company oose Innovative Informatik eG located in Hamburg.
Before he joined oose, Stephan worked for many years as a software
developer, software architect, and systems engineer in the field of radio
reconnaissance and communication intelligence systems. He has
developed sophisticated applications, especially for distributed systems
with ambitious performance requirements, and graphical user interfaces
using C++ and other programming languages. Stephan is also a speaker
at professional conferences and author of several publications. As a
member of the Gesellschaft für Systems Engineering e.V., the German
chapter of the international Systems Engineering organization INCOSE, he is also engaged in the Systems
Engineering community. Furthermore, he is an active supporter of the Software Craftsmanship movement
and concerned with principles and practices of Clean Code Development (CCD).
Stephan Roth lives with his wife Caroline and their son Maximilian in Bad Schwartau, a spa in the
German federal state of Schleswig-Holstein near the Baltic Sea.
You can visit Stephan’s website and blog about Systems Engineering, Software Engineering, and Software
Craftsmanship via the URL roth-soft.de. Please note that the articles there are mainly written in German.
On top of that, you can contact him via e-mail or follow him at the networks listed below.
E-Mail: stephan@clean-cpp.com
Twitter: @_StephanRoth (https://twitter.com/_StephanRoth)
Google+ Profile Page: http://gplus.to/sro
LinkedIn: http://www.linkedin.com/pub/stephan-roth/79/3a1/514

xiii
About the Technical Reviewer

Marc Gregoire is a software engineer from Belgium. He graduated from the University of Leuven, Belgium,
with a degree in "Burgerlijk ingenieur in de computer wetenschappen" (equivalent to Master of Science
in engineering in computer science). The year after, he received a master’s degree, cum laude, in artificial
intelligence at the same university. After his studies were completed, Marc started working for a software
consultancy company called Ordina Belgium. As a consultant, he worked for Siemens and Nokia Siemens
Networks on critical 2G and 3G software running on Solaris for telecom operators. This required working in
international teams stretching from South America and the United States to EMEA and Asia. Marc is now
working for Nikon Metrology on industrial 3D laser scanning software.
His main expertise is C/C++, and specifically Microsoft VC++ and the MFC framework. He has
experience in developing C++ programs running 24x7 on Windows and Linux platforms: for example, KNX/
EIB home automation software. Next to C/C++, Marc also likes C# and uses PHP for creating web pages.
Since April 2007, he has received the yearly Microsoft MVP (Most Valuable Professional) award for his
Visual C++ expertise.
Marc is the founder of the Belgian C++ Users Group (www.becpp.org), author of Professional C++ and a
member of the CodeGuru forum (as Marc G). He maintains a blog on www.nuonsoft.com/blog/.

xv
Acknowledgments

Writing a book like this one is never just the work of an individual person, the author. There are always
numerous, fabulous people who contribute significantly to such a great project.
First of all, I would like to thank Steve Anglin of Apress. Steve contacted me in March 2016 and has
persuaded me to continue my book project with Apress Media LLC, which has been self-published at
Leanpub until then. That was such great luck, and I thank you, dear Steve. In July 2016 the contracts were
signed. Nevertheless, I would also like to thank the superb Leanpub self-publishing platform that served
some years as a kind of "incubator" for this book.
Next, I would like to thank Mark Powers, Editorial Operations Manager at Apress, for his great support
during the writing of the manuscript. Mark was not only always available to answer questions: his incessant
follow-up on the progress of the manuscript was a positive incentive for me. I am very grateful to you, dear
Mark. In addition, many thanks also to Matthew Moodie, Lead Development Editor at Apress, who has
provided proper help throughout the whole book development process.
A special thank you goes out to my technical reviewer Marc Gregoire. Marc, thank you for critically
examining every single chapter. You’ve found many issues that I probably would have never found. You
pushed me hard to improve several sections, and that was really valuable to me.
Of course, I would also like to say a big thank you to the whole production team at Apress. They’ve done
an excellent job regarding the finalization (copy editing, indexing, composition/layout, etc.) of the whole
book until the distribution of the final print (and eBook) files.
Of course, I also thank all my colleagues at oose. Thank you for the many inspiring discussions.
Last but not least, I would like to thank my beloved and unique family, especially for their
understanding that a book project takes a great deal of time. Maximilian and Caroline, you’re just wonderful.

xvii

You might also like