- •Table of Contents
- •About the Author
- •About the Technical Reviewer
- •Acknowledgments
- •Software Entropy
- •Clean Code
- •C++11: The Beginning of a New Era
- •Who This Book Is For
- •Conventions Used in This Book
- •Sidebars
- •Notes, Tips, and Warnings
- •Code Samples
- •Coding Style
- •C++ Core Guidelines
- •Companion Website and Source Code Repository
- •UML Diagrams
- •The Need for Testing
- •Unit Tests
- •What About QA?
- •Rules for Good Unit Tests
- •Test Code Quality
- •Unit Test Naming
- •Unit Test Independence
- •One Assertion per Test
- •Independent Initialization of Unit Test Environments
- •Exclude Getters and Setters
- •Exclude Third-Party Code
- •Exclude External Systems
- •What Do We Do with the Database?
- •Don’t Mix Test Code with Production Code
- •Tests Must Run Fast
- •How Do You Find a Test’s Input Data?
- •Equivalence Partitioning
- •Boundary Value Analysis
- •Test Doubles (Fake Objects)
- •What Is a Principle?
- •KISS
- •YAGNI
- •It’s About Knowledge!
- •Building Abstractions Is Sometimes Hard
- •Information Hiding
- •Strong Cohesion
- •Loose Coupling
- •Be Careful with Optimizations
- •Principle of Least Astonishment (PLA)
- •The Boy Scout Rule
- •Collective Code Ownership
- •Good Names
- •Names Should Be Self-Explanatory
- •Use Names from the Domain
- •Choose Names at an Appropriate Level of Abstraction
- •Avoid Redundancy When Choosing a Name
- •Avoid Cryptic Abbreviations
- •Avoid Hungarian Notation and Prefixes
- •Avoid Using the Same Name for Different Purposes
- •Comments
- •Let the Code Tell the Story
- •Do Not Comment Obvious Things
- •Don’t Disable Code with Comments
- •Don’t Write Block Comments
- •Don’t Use Comments to Substitute Version Control
- •The Rare Cases Where Comments Are Useful
- •Documentation Generation from Source Code
- •Functions
- •One Thing, No More!
- •Let Them Be Small
- •“But the Call Time Overhead!”
- •Function Naming
- •Use Intention-Revealing Names
- •Parameters and Return Values
- •Avoid Flag Parameters
- •Avoid Output Parameters
- •Don’t Pass or Return 0 (NULL, nullptr)
- •Strategies for Avoiding Regular Pointers
- •Choose simple object construction on the stack instead of on the heap
- •In a function’s argument list, use (const) references instead of pointers
- •If it is inevitable to deal with a pointer to a resource, use a smart one
- •If an API returns a raw pointer...
- •The Power of const Correctness
- •About Old C-Style in C++ Projects
- •Choose C++ Strings and Streams over Old C-Style char*
- •Use C++ Casts Instead of Old C-Style Casts
- •Avoid Macros
- •Managing Resources
- •Resource Acquisition Is Initialization (RAII)
- •Smart Pointers
- •Unique Ownership with std::unique_ptr<T>
- •Shared Ownership with std::shared_ptr<T>
- •No Ownership, but Secure Access with std::weak_ptr<T>
- •Atomic Smart Pointers
- •Avoid Explicit New and Delete
- •Managing Proprietary Resources
- •We Like to Move It
- •What Are Move Semantics?
- •The Matter with Those lvalues and rvalues
- •rvalue References
- •Don’t Enforce Move Everywhere
- •The Rule of Zero
- •The Compiler Is Your Colleague
- •Automatic Type Deduction
- •Computations During Compile Time
- •Variable Templates
- •Don’t Allow Undefined Behavior
- •Type-Rich Programming
- •Know Your Libraries
- •Take Advantage of <algorithm>
- •Easier Parallelization of Algorithms Since C++17
- •Sorting and Output of a Container
- •More Convenience with Ranges
- •Non-Owning Ranges with Views
- •Comparing Two Sequences
- •Take Advantage of Boost
- •More Libraries That You Should Know About
- •Proper Exception and Error Handling
- •Prevention Is Better Than Aftercare
- •No Exception Safety
- •Basic Exception Safety
- •Strong Exception Safety
- •The No-Throw Guarantee
- •An Exception Is an Exception, Literally!
- •If You Can’t Recover, Get Out Quickly
- •Define User-Specific Exception Types
- •Throw by Value, Catch by const Reference
- •Pay Attention to the Correct Order of Catch Clauses
- •Interface Design
- •Attributes
- •noreturn (since C++11)
- •deprecated (since C++14)
- •nodiscard (since C++17)
- •maybe_unused (since C++17)
- •Concepts: Requirements for Template Arguments
- •The Basics of Modularization
- •Criteria for Finding Modules
- •Focus on the Domain of Your Software
- •Abstraction
- •Choose a Hierarchical Decomposition
- •Single Responsibility Principle (SRP)
- •Single Level of Abstraction (SLA)
- •The Whole Enchilada
- •Object-Orientation
- •Object-Oriented Thinking
- •Principles for Good Class Design
- •Keep Classes Small
- •Open-Closed Principle (OCP)
- •A Short Comparison of Type Erasure Techniques
- •Liskov Substitution Principle (LSP)
- •The Square-Rectangle Dilemma
- •Favor Composition over Inheritance
- •Interface Segregation Principle (ISP)
- •Acyclic Dependency Principle
- •Dependency Inversion Principle (DIP)
- •Don’t Talk to Strangers (The Law of Demeter)
- •Avoid Anemic Classes
- •Tell, Don’t Ask!
- •Avoid Static Class Members
- •Modules
- •The Drawbacks of #include
- •Three Options for Using Modules
- •Include Translation
- •Header Importation
- •Module Importation
- •Separating Interface and Implementation
- •The Impact of Modules
- •What Is Functional Programming?
- •What Is a Function?
- •Pure vs Impure Functions
- •Functional Programming in Modern C++
- •Functional Programming with C++ Templates
- •Function-Like Objects (Functors)
- •Generator
- •Unary Function
- •Predicate
- •Binary Functors
- •Binders and Function Wrappers
- •Lambda Expressions
- •Generic Lambda Expressions (C++14)
- •Lambda Templates (C++20)
- •Higher-Order Functions
- •Map, Filter, and Reduce
- •Filter
- •Reduce (Fold)
- •Fold Expressions in C++17
- •Pipelining with Range Adaptors (C++20)
- •Clean Code in Functional Programming
- •The Drawbacks of Plain Old Unit Testing (POUT)
- •Test-Driven Development as a Game Changer
- •The Workflow of TDD
- •TDD by Example: The Roman Numerals Code Kata
- •Preparations
- •The First Test
- •The Second Test
- •The Third Test and the Tidying Afterward
- •More Sophisticated Tests with a Custom Assertion
- •It’s Time to Clean Up Again
- •Approaching the Finish Line
- •Done!
- •The Advantages of TDD
- •When We Should Not Use TDD
- •TDD Is Not a Replacement for Code Reviews
- •Design Principles vs Design Patterns
- •Some Patterns and When to Use Them
- •Dependency Injection (DI)
- •The Singleton Anti-Pattern
- •Dependency Injection to the Rescue
- •Adapter
- •Strategy
- •Command
- •Command Processor
- •Composite
- •Observer
- •Factories
- •Simple Factory
- •Facade
- •The Money Class
- •Special Case Object (Null Object)
- •What Is an Idiom?
- •Some Useful C++ Idioms
- •The Power of Immutability
- •Substitution Failure Is Not an Error (SFINAE)
- •The Copy-and-Swap Idiom
- •Pointer to Implementation (PIMPL)
- •Structural Modeling
- •Component
- •Interface
- •Association
- •Generalization
- •Dependency
- •Template and Template Binding
- •Behavioral Modeling
- •Activity Diagram
- •Action
- •Control Flow Edge
- •Other Activity Nodes
- •Sequence Diagram
- •Lifeline
- •Message
- •State Diagram
- •State
- •Transitions
- •External Transitions
- •Internal Transitions
- •Trigger
- •Stereotypes
- •Bibliography
- •Index
Chapter 7 Functional Programming
Listing 7-21. Putting Every Single Word in a List in Angle Brackets
#include <algorithm> #include <iostream>
#include <string> #include <vector>
int main() {
std::vector<std::string> quote { "That's", "one", "small", "step", "for", "a", "man,", "one", "giant", "leap", "for", "mankind." }; std::vector<std::string> result;
std::transform(begin(quote), end(quote), back_inserter(result), [](const std::string& word) { return "<" + word + ">"; });
std::for_each(begin(result), end(result),
[](const std::string& word) { std::cout << word << " "; });
return 0;
}
The output of this small program is as follows:
<That's> <one> <small> <step> <for> <a> <man,> <one> <giant> <leap> <for> <mankind.>
Generic Lambda Expressions (C++14)
With C++14, lambda expressions experienced additional improvements. Since C++14, it is okay to use auto (see the section about automatic type deduction in Chapter 5) as the return type of a function or a lambda. In other words, the compiler will deduce the type. Such lambda expressions are called generic lambda expressions.
Listing 7-22 shows an example.
318
Chapter 7 Functional Programming
Listing 7-22. Applying a Generic Lambda Expression on Values of Different Data Type
#include <complex> #include <iostream>
int main() {
auto square = [](const auto& value) noexcept { return value * value; };
const auto result1 = square(12.56); const auto result2 = square(25u); const auto result3 = square(-6);
const auto result4 = square(std::complex<double>(4.0, 2.5));
std::cout << "result1 is " << result1 << "\n"; std::cout << "result2 is " << result2 << "\n"; std::cout << "result3 is " << result3 << "\n"; std::cout << "result4 is " << result4 << std::endl;
return 0;
}
The parameter type as well as the result type are derived automatically depending on the type of the concrete parameter (literal) when the function is compiled (in
the previous example, double, unsigned int, int, and a complex number of type std::complex<T>). Generalized lambdas are extremely useful in interaction with Standard Library algorithms, because they are universally applicable.
Lambda Templates (C++20)
The C++17 language standard that followed C++14 extended the capabilities of C++ lambdas. For instance, with C++17, it became possible to evaluate lambdas at compile- time, so-called constexpr lambdas. The new C++20 standard also offers further, mostly smaller improvements regarding more convenient uses of lambdas and to allow some advanced use cases.
However, one new C++20 add-on regarding lambda expressions is explicitly noteworthy: lambda templates!
319
Chapter 7 Functional Programming
Maybe you are a little surprised now and ask yourself, wait a minute! We have had generic lambdas since C++14. That is actually something like templates. For what purpose do we still need lambda templates now?
Let’s compare two lambda expressions for a multiplication, one implemented as a generic lambda (C++14) and one as a template lambda (C++20):
auto multiply1 = [](const auto multiplicand, const auto multiplier) { return multiplicand * multiplier;
};
auto multiply2 = []<typename T>(const T multiplicand, const T multiplier) { return multiplicand * multiplier;
};
If you would call them with identical parameters for both arguments, you will not notice a difference:
auto result1 = multiply1(10, 20); auto result2 = multiply2(10, 20);
In both cases, the value 200 can be found in the variables that receive the results. But what will happen if we call both variants with parameters of different types, e.g., an int for the multiplicand and a bool for the multiplier?
auto result3 = multiply1(10, true); auto result4 = multiply2(10, true);
Also in this case the compiler manages to translate the generic template multiply1 without complaint. (By the way, the result in result3 is 10 because the compiler expands the true to an int [integral promotion] and has the value 1.) However, we get a compiler error for the instantiation of the lambda template multiply2; for instance something like this:
error: deduced conflicting types for parameter 'T' ('int' and 'bool')
With lambda templates, developers cannot be prevented from accidental wrong instantiations or usages of lambdas. Furthermore, C++20 concepts (see the section entitled “Concepts: Requirements for Template Arguments” in Chapter 5) can of course be used to perform compile-time validations of a lambda’s template arguments. See Listing 7-23.
320
Chapter 7 Functional Programming
Listing 7-23. Lambda Templates Can Also Be Equipped with Constraints Using C++20 Concepts
#include <concepts> #include <iostream>
#include <string>
template <typename T>
concept Number = std::integral<T> || std::floating_point<T>;
int main() {
auto add = [] <Number T> (const T addend1, const T addend2) { return addend1 + addend2;
};
const std::string string1 { "Hello" }; const std::string string2 { "World" };
auto result1 |
= add(10, 20); |
// |
OK |
||
auto result2 |
= add('x', 'y'); |
|
// OK |
||
auto |
result3 |
= |
add(10.0, 20.0); |
// OK |
|
auto |
result4 |
= |
add(string1, string2); // Compiler-error: constraints not |
||
|
|
|
|
satisfied! |
std::cout << result1 << ", " << result2 << ", " << result3 << std::endl;
return 0;
}
In this example, the lambda template is allowed only for use with numeric data types (int, float, double, ...). Although there is an operator called std::string::operator+ that allows two strings to be concatenated, an instantiation of the lambda template is prohibited by the Number<T> concept.
321