- •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-9. Filling a Vector with 100 Random Numbers
#include "RandomGenerator.h" #include <algorithm> #include <functional> #include <iostream>
#include <vector>
using Numbers = std::vector<short>;
const std::size_t AMOUNT_OF_NUMBERS { 100 };
Numbers createVectorFilledWithRandomNumbers() { RandomNumberGenerator<short> randomNumberGenerator { }; Numbers randomNumbers(AMOUNT_OF_NUMBERS);
std::generate(begin(randomNumbers), end(randomNumbers), std::ref(randomNu mberGenerator));
return randomNumbers;
}
void printNumbersOnStdOut(const Numbers& numbers) { for (const auto& number : numbers) {
std::cout << number << std::endl;
}
}
int main() {
auto randomNumbers = createVectorFilledWithRandomNumbers(); printNumbersOnStdOut(randomNumbers);
return 0;
}
Unary Function
Next, let’s look at an example of a unary function-like object, which is a functor whose parenthesis operator has one parameter. See Listing 7-10.
306
Chapter 7 Functional Programming
Listing 7-10. An Example of a Unary Functor
class ToSquare { public:
[[nodiscard]] constexpr int operator()(const int value) const noexcept { return value * value; }
};
As its name suggests, this functor squares the values passed to it in the parenthesis operator. This does not necessarily always have to be the case, because, a unary functor can also have private member variables, and thus a mutable state. Read or write access to global variables is also possible (...although this should not be the normal case nowadays).
With the ToSquare functor, we can now extend the previous example and apply it to the vector with the ascending integer sequence. See Listing 7-11.
Listing 7-11. All 100 Numbers in a Vector Are Squared
#include <algorithm>
#include <vector>
using Numbers = std::vector<int>;
int main() {
const std::size_t AMOUNT_OF_NUMBERS { 100 }; Numbers numbers(AMOUNT_OF_NUMBERS);
std::generate(begin(numbers), end(numbers), IncreasingNumberGenerator()); std::transform(begin(numbers), end(numbers), begin(numbers), ToSquare()); // ...to be continued...
return 0;
}
The used algorithm std::transform (defined in the <algorithm> header) applies the given function or function object to a range (defined by the first two parameters) and stores the result in another range (defined by the third parameter). In our case, these ranges are the same.
307
Chapter 7 Functional Programming
Predicate
Predicates are a special kind of functor. A unary functor is called a unary predicate if it has one parameter and a Boolean return value indicating a true or false result of some test, such as shown in Listing 7-12.
Listing 7-12. An Example of a Predicate
class IsAnOddNumber { public:
[[nodiscard]] constexpr bool operator()(const int value) const noexcept { return (value % 2) != 0;
}
};
This predicate can now be applied to our number sequence using the std::erase_ if algorithm to get rid of all the odd numbers. See Listing 7-13.
Listing 7-13. All Odd Numbers From the Vector Are Deleted Using std::erase_if
#include <algorithm>
#include <vector>
// ...
using Numbers = std::vector<int>;
int main() {
const std::size_t AMOUNT_OF_NUMBERS = 100; Numbers numbers(AMOUNT_OF_NUMBERS);
std::generate(begin(numbers), end(numbers), IncreasingNumberGenerator()); std::transform(begin(numbers), end(numbers), begin(numbers), ToSquare()); std::erase_if(numbers, IsAnOddNumber());
// ...
return 0;
}
308
Chapter 7 Functional Programming
Note Unless you are using the C++20 language standard, you will need to apply the Erase-Remove idiom to remove the odd numbers from the vector, which is explained in a sidebar in the section entitled “Building Abstractions Is Sometimes Hard” in Chapter 3.
In order to use a functor in a more flexible and generic way, it is usually implemented as a class template. Therefore, we can refactor our unary functor IsAnOddNumber into a class template so that it can be used with all integral types, such as short, int, unsigned int, uint64_t, etc. This can easily be done with the new C++20 concepts, as shown in Listing 7-14.
Listing 7-14. Ensuring That the Template Parameter Is an Integral Data Type
#include <concepts>
template <std::integral T> class IsAnOddNumber { public:
[[nodiscard]] constexpr bool operator()(const T value) const noexcept { return (value % 2) != 0;
}
};
The location within the body of the main() function, where our predicate is used (the call of the std::erase_if function), must now be adjusted a little bit:
// ...
std::erase_if(numbers, IsAnOddNumber<Numbers::value_type>());
// ...
If we inadvertently use the IsAnOddNumber template with a non-integral data type, such as a double, we would get a meaningful error message from the compiler.
Listing 7-15 shows the entire example, completed with an output of the contents of the vector on stdout, using std::for_each and the PrintOnStdOut functor.
309
Chapter 7 Functional Programming
Listing 7-15. The Whole Code Example with All Three Types of Functors
#include <algorithm> #include <concepts> #include <iostream>
#include <vector>
class IncreasingNumberGenerator { public:
[[nodiscard]] int operator()() noexcept { return number++; }
private:
int number { 0 };
};
class ToSquare { public:
[[nodiscard]] constexpr int operator()(const int value) const noexcept { return value * value;
}
};
template <std::integral T> class IsAnOddNumber { public:
[[nodiscard]] constexpr bool operator()(const T value) const noexcept { return (value % 2) != 0;
}
};
class PrintOnStdOut { public:
void operator()(const auto& printable) const { std::cout << printable << '\n';
}
};
using Numbers = std::vector<int>;
310