Diagrams for the book, trending toward a C4-style standard.
Click any diagram to open it fullscreen. Each is
also available as .excalidraw source; open it on
excalidraw.com
to edit.
Ch. 0
The local build-and-test loop
Every example in this book follows the same loop: edit source, resolve dependencies with conan install, configure with cmake --preset, build with clang, and verify with ctest, then observe the behavior a chapter claims. A failing test sends you back to the source. Both presets, cpp23 (default) and cpp20 (compat), run this identical loop on the host, no containers.
The book's arc: recognize the forces, name a candidate pattern (or non-pattern), choose the idiomatic C++ expression, test it with gtest, and know when not to use it. Forces and trade-offs run under every step.
A pattern name sits between three readers, a teammate, a future-you, and an AI assistant, compressing a cluster of forces and a chosen structure into one word all three can act on the same way.
One Invoice type doing three jobs, split by SRP into three focused types, extended by OCP through an InvoiceRule abstraction, and refined by LSP without breaking the base contract.
The Liskov clamp, an overridable hook inside a sealed sequence
A subtotal flows through the overridable discount_rate() hook into a clamp the base method owns and never exposes, so every subtype's rate is bounded before it reaches the subtotal.
DIP routes a high-level policy through an abstraction instead of straight to a concrete gateway, inverting the dependency arrow. ISP splits that abstraction into role interfaces a concrete type implements only where it has the capability.
RAII lifecycle: acquire in the constructor, release in the destructor
A thrown exception during use still funnels into the same release point as a normal return: the DockBayLease destructor runs during stack unwinding exactly as it would on a clean exit, so the resource never stays held past the scope that acquired it.
A move hands ownership from one dock-bay lease to another and flips the source to owning nothing, so both objects destruct but the registry releases exactly once.
unique_ptr as a sole owner, shared_ptr as a ref-counted shared owner, and weak_ptr observing without owning to break what would otherwise be a reference cycle.
Each style, fixture, parameterized, typed, mock-interaction, and death test, answers a different question, and all of them funnel into the same CTest discovery and run flow.
A checkout Context holds one interchangeable shipping-cost strategy at a time, expressed as runtime polymorphism, a value-semantic std::function, or a compile-time concept policy, trading runtime flexibility against zero overhead.
An order-export pipeline runs a fixed sequence and calls private virtual hooks in a fixed order; concrete exporters override the hooks without touching the sequence or the validate and trailer invariants.
One rule set, four finite-state-machine representations
The same shipment transition rules as a GoF state hierarchy, a transition table, a std::variant with std::visit, and a stochastic machine that draws its own next state.
An invoker drains a FIFO command queue into a receiver, and a CommandHistory moves a command between a done stack and an undone stack as undo and redo run.
An abstract factory producing two matching carrier families
CarrierIntegrationFactory declares a family of three abstract products; the FastShip and SummitFreight factories each implement and create their own matching family, and the client depends only on the abstractions.
Factory Method, a fixed sequence around one varying hook
onboard() runs a fixed sequence around the create_test_suite() hook, which the sandbox and production onboarders each fill with a different test suite, one product decided by environment.
Builder, prototype registry, and a serialization round trip
A builder assembles a manifest behind a fluent interface and validates it once at build(); a prototype registry clones a named template into an independent copy; and serialize then deserialize round-trips the result through plain text.
A singleton's clients reach into one global instance directly; the DI alternative routes the same capability through an abstraction a composition root wires, swappable with a test double.
Adapter wraps a legacy API behind a target interface; Facade fronts three subsystems with one call; Bridge crosses an abstraction axis of refined notification kinds with an implementation axis of transports.
Bridge, two axes giving N plus M classes instead of N times M
Two notification kinds crossed with two transports give four live combinations from two small hierarchies, not the class-per-combination explosion a single hierarchy would need.
A decorator stack (surcharge, caching, logging) wraps a core rate source, next to a proxy controlling access to a real manifest store. Both wrap the same interface their subject implements; only the intent differs.
Reordering the cache and surcharge decorators changes which total a repeat call returns, because a cache hit short-circuits before the layer beneath it runs again.
A composite tree (pallet, cartons, items) sharing one interface on the left, and a flyweight pool of SKU descriptors referenced by many line items on the right.
A subject fans a status change out to independent observers, next to a mediator routing between collaborators that never reference each other directly, shown against the tangled direct mesh it replaces.
A handler chain and an iterator or ranges traversal
A request flows down a chain of handlers that each handle or pass, next to an aggregate traversed by a hand-written forward iterator and by a filter plus transform ranges pipeline over the same data.
Visitor and Interpreter over a shared AST, plus Memento
A shared rule-node AST walked two ways, a classic double-dispatch visitor and a std::variant plus std::visit visitor producing the same result, with an interpreter walking the same AST, next to an editor whose memento captures and restores its whole state.
Memento, save and restore a whole state through an opaque token
The editor saves its whole state into a snapshot a caretaker can hold and return but cannot read, and restore() swaps that state back in a single call.
CRTP resolves a derived type at compile time instead of through a vtable, and a policy host is composed from interchangeable compile-time policies the same way.
A value-semantic wrapper erases unrelated concrete types behind a hand-written concept and model with no shared base class, next to a class that exposes only its header across a PImpl firewall, its implementation reachable through nothing but a pointer.
An expression template defers a weighted sum into a tree of scaled and sum nodes that evaluates once into a single result, against the eager version that builds a new object at every operator.
A self-registering prototype registry across translation units
Each carrier policy's translation unit registers its own prototype at static initialization, so a caller resolves a key through the registry and gets back a fresh clone with no central file naming any concrete type.
A caller acquires a resource from a bounded pool through an RAII lease that returns it on destruction, the shape that also underlies a connection pool, a thread pool, a monitor object, and an active object.
A thread pool's shared queue serves several workers pulling concurrently, while an active object's private queue serves one dedicated worker in submission order and the caller never blocks.
A shipment message type selects its handler three ways, an enum-indexed function-pointer table, an open unordered_map, and a compile-time constexpr array, each a lighter stand-in for a Strategy, State, or Command hierarchy.
Over-patterned design versus the simplified rewrite
A singleton registry, a factory-of-factories, and a god object on one side, collapsed on the other into one service that takes a settings value by injection, which is what makes the rewrite testable in isolation.
The same code shown three ways: hard-wired to the wall clock with no seam, an object seam that injects a Clock so a test can substitute it, and a link seam that swaps a grace-period policy at link time with no object to inject into.
Breaking a hard-wired dependency behind an interface
A direct call to a concrete collaborator, replaced by an extracted interface that both a production implementation and a test double satisfy, so the once hard-wired dependency becomes substitutable under test.
A port and a delegator put a seam in front of an untouched static lookup so a new caller can inject a test double, while the legacy call site keeps calling the static method directly.
A two-stage pipeline: Feathers first to characterize and break dependencies into a safety net, then Fowler's named refactorings applied on the now-tested code, with the handoff being the point a safety net exists.
Callers reach a stable pricing interface; a router sends traffic to the legacy implementation, the new one, or both in compare mode, shifting customer by customer until the new implementation passes the same characterization suite.
A shipment dispatcher composes Factory, Strategy, State, Command with undo, and Observer, with the events and calls flowing between them: a state transition fires observer notifications, a command invokes the factory-built strategy, and an undo restores the prior snapshot.
One shipment's run in order across the five composed patterns, with the same RateStrategy instance quoting the opening rate and the corrected rate after a weight change.
The engineer names the forces and the candidate pattern, an AI drafts an implementation, and a verification gate of behavior tests and an idiomatic review decides whether the draft is accepted or sent back, keeping responsibility for correctness with the engineer.
The programming-principle vocabulary, grouped into six families
Six families of principle: a tight SOLID recap, simplicity and scope, structure and change, coupling and cohesion, interoperability and resilience, and a process family with no code shape at all, each a different angle on the same question of what force justifies a given design.
Breaking a physical dependency cycle by levelizing
Shipment and Carrier as a cyclic include graph, redrawn as a levelized directed acyclic graph where a higher-level coordinator depends down on both peers so neither peer names the other.