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
Editing a source file, running dotnet build, then the xUnit v3 suite forms one loop against net10.0: a failing assertion sends you back to the source. The loop runs inside a single example and again across every example through scripts/verify.sh.
Three competing forces, accuracy, speed, and changeability, each pull a rate-quote design in a different direction. The eventual decision is the compromise point among all three, not a win for any single force.
Starting from forces versus starting from a pattern name
Two starting points for the same rate-quote decision. Starting from forces lets accuracy, speed, and changeability converge on a fitting shape; starting from a pattern name reaches for a four-part structure before any force is examined.
Observer, Strategy, and Null Object each existed to compensate for a gap in earlier object-oriented languages. C# closes each gap directly: the event keyword generates the subscriber list, a delegate replaces the strategy interface, and nullable reference types replace the stand-in object.
Ten C# language and runtime features, each mapped against the pattern shape it reshapes: events, delegates, LINQ, nullable reference types, extension members, expression trees, source generators, generics, static abstract members, and value types.
A single compile-and-run pipeline for a generic container. Roslyn compiles each closed generic as a separate instantiation, and the CLR JIT produces distinct, specialized runtime types that store elements inline with no boxing. Reification is a CLR guarantee since .NET's first release.
One name, Cleared, read the same way by an engineer, a teammate, and an AI assistant, each checking the same precondition and postcondition against the code. The name carries across the full consignment lifecycle from booking to delivery.
An overloaded rate calculator resolved into single-responsibility collaborators such as IRateQuote. A surcharge decorator composes an open extension point for Open/Closed, and two pricing calculators substitute for each other through that same contract for Liskov Substitution.
A fat carrier-gateway interface splits into narrow rate and tracking abstractions. One consumer depends on the narrow abstraction, another depends on the full gateway, never on a concrete implementation; the built-in DI container is the one place that resolves an abstraction to a concrete type.
One singleton registration fans out through three factory registrations, all resolving back to the same instance. Each consumer takes exactly the interface face it needs, a narrow rates view or the full gateway, from one shared registration.
A synchronous using scope and an asynchronous await using scope shown side by side. Both run cleanup the moment the scope exits rather than waiting on the garbage collector: one closes a file handle immediately, the other awaits a flush before closing.
Three dispose shapes compared: a sealed type owning only managed disposables needs just a guarded Dispose, an unsealed type owning an unmanaged handle needs the heavier finalizer pattern, and a type whose release must await a flush implements IAsyncDisposable instead.
Inline values and zero-allocation field projection
Two record struct values compared side by side, equal by content rather than reference, against a reference-type class for contrast. A fixed-width record is sliced in place into its typed fields with no intermediate string allocation.
A fixed-width record laid out as a ruler of labeled field spans at their exact offsets. Each span slices directly into its typed destination, and every slice is a window over the same backing characters rather than its own allocated string.
A record with expression, copy then change, original untouched
A consignment record amended through a with expression. The original keeps its required and init members exactly as they were, including a nested route. The with expression copies every member into a new object and overrides only the route, leaving the first untouched.
The required and init contract, compiles versus CS9035
A record's members side by side: required init-only fields, an init accessor settable only during construction, a legitimately absent optional field, and a plain field with its own default. Omitting a required member fails at compile time, never as a suppressible warning.
ShipmentRatingEngine under a four-phase test with NSubstitute doubles
The four-phase test around a rating engine. Arrange creates NSubstitute doubles for its collaborators and stubs their return values, Act calls the method once, and Assert checks both the returned result and that each substitute was called as expected.
A substitute's two jobs, stubbing on Arrange and verifying on Assert
The same NSubstitute double doing two jobs. Arrange stubs a return value, including an async case and per-argument stubbing. Assert reads back what the substitute recorded, using argument matchers that work on both the stubbing and verification sides.
The same rate-pricing strategy supplied three ways: a plain delegate with no interface or class, a named interface giving several tariffs a shared contract, and a keyed DI container resolving the same tariffs by a runtime string key. All three return the same quote.
Keyed resolution, an unrecognized key, and the non-keyed trap
Three pricing strategies are registered as keyed singletons. One consumer resolves the matching strategy at runtime; another binds a fixed key at construction. An unrecognized key throws or returns null depending on the method, and a keyless lookup returns null even with keyed registrations present.
The same three-step customs workflow built two ways. The inheritance form seals the step order on an abstract builder so no subclass can reorder it; the delegate form moves that order into an engine taking functions supplied per country instead of a subclass.
Three fixed workflow slots run in the same order for every country. Each slot's position never moves; only its content changes, as each country supplies its own required fields, duty formula, and validation threshold.
The consignment lifecycle as a finite state machine
A state machine drives a consignment through its lifecycle from booked to delivered on a sequence of events. One state the enum defines is never reached by this machine. An unmatched status-and-event pair is rejected with an exception rather than ignored.
A probabilistic machine draws a value from an injected random source while a consignment is in transit. A low draw delays it and loops back for a retry; a higher draw clears and delivers it. A seeded source keeps the simulation replayable and testable.
A command interface's execute and undo methods back four command shapes acting on the same mutable booking, each snapshotting what it changes. A queue runs commands first-in-first-out, then unwinds its history last-in-first-out on undo, moving commands back and forth without reconstructing them.
An async queue awaits each queued command's execute method in strict order before dequeuing the next. Undo walks the executed history backward one command at a time, and a cancellation token threads unchanged through every call beneath it.
One overridable step, one matched family, one type-keyed registry
A dispatcher fixes a build, send, parse sequence and leaves gateway creation as its one overridable step. An abstract factory produces a matched gateway, request builder, and response parser as one family per carrier, and a registry stores each family keyed by its carrier type.
Registering, resolving, and extending by typeof(T)
A registry writes a factory into a dictionary keyed by carrier type and reads it back by that key with no cast required. Adding a carrier costs one registration call with no edit to the registry; an unregistered carrier throws rather than returning null.
Three paths reach the same booking request: an object initializer that fails to compile on a missing required member, a builder that raises an exception on an invalid field, and a cloned template amended with a with expression. All three produce an equal record value.
with leaves the template untouched, the spread leaves it unchanged
Cloning a template with a with expression copies every member and overrides only the ones named, leaving the template itself untouched. Because a reference-typed member is shared rather than copied, a collection-expression spread replaces that member with a new list instead, growing only the clone.
One tariff table, three ways to guarantee one instance
A tariff table guarantees a single instance three ways: a private constructor with a static property, a lazily built value, and a DI singleton registration with no static field at all. Scoped and transient registrations of the same source contrast the lifetimes beyond singleton.
A singleton resolution returns the identical instance every time, a transient resolution returns a new instance every call, and a scoped resolution stays the same within one scope but differs in the next. A captive scoped dependency under a singleton becomes a startup-validation exception instead.
Three carriers, one gateway, one booking call, one label
Three native carrier clients with nothing in common are each adapted to the same gateway interface. A facade sequences address validation, that adapted gateway, and customs filing behind one booking call. A label abstraction lets its content and its rendering format vary independently.
Implicit for a safe widening, explicit for anything that can lose data
A money type converts to decimal implicitly because the conversion is always exact; converting back is explicit because some values cannot round-trip without loss. A weight type converts explicitly in both directions, since a unit change rather than rounding is what the cast signals.
A fixed wrapping order and a cache standing in the same place
A base rate calculator is wrapped by a discount, then a surcharge, then a tax decorator, each implementing the same interface as the layer underneath. A caching proxy answers a repeated request from its own cache instead of the slow gateway.
A composition root that wraps, and a proxy that intercepts
A composition root registers a rate calculator as a factory that wraps the base implementation in every decorator, so every consumer resolves the same wrapped chain. A dynamic proxy intercepts each call, records the invoked member, and forwards it to its target.
One interface for a leaf and a branch, one instance per code
A shared interface gives a leaf and a branch the same weight and enumeration surface, so a branch sums and flattens its children recursively regardless of nesting. A registry builds its values once and hands back the same shared instance on every later lookup.
FrozenDictionary once, shared instances or a named exception after
Two registries each build their lookup table once into a frozen dictionary, then serve every lookup from that read-optimized structure. A known code returns the identical interned instance every time; an unrecognized code throws a named exception instead.
An event with two subscribers and a retained history
A tracker declares one event and raises it through a null-conditional invoke, so nobody listening never causes a throw. Two independent subscribers can attach and detach without affecting each other, and every event is appended to a retained history regardless of who was listening.
A stream wraps a reactive subject and exposes only its observable half, so a caller can subscribe but never push a value directly. Because the subject has no replay buffer, an observer subscribing late misses earlier events, the gap the retained-history tracker never leaves open.
Four stages in order, a halt, and a mediator that picks the route
A clearance pipeline wires four stages into one chain, each recording its name into a shared context and passing the declaration on only while the result stays cleared. A halt stops the chain. A separate mediator routes between two colleagues that never reference each other.
Two colleagues, one mediator, and no echo back to the sender
A mediator is the only thing two colleagues depend on to reach each other. Sending a message hands the mediator a reference to the sender, never a recipient's name, and the mediator routes by checking identity and delivering to whichever colleague did not send it.
Paginate validates, PaginateIterator is what yield return becomes
A pagination method validates its page size up front, then delegates the work to a private iterator method. That iterator's yield-return body becomes a compiler-generated state machine producing one page at a time instead of building the whole list up front.
StreamAsync's IAsyncEnumerable, pulled by await foreach, cut short by break
An async stream exposes a cancellation token that an await-foreach consumer can reach directly instead of a compiler-generated default. One consumer reads the stream to completion, while another breaks out early, disposing the enumerator and skipping every later event.
One eager check, two deferred sequences, nothing runs before a pull
A pagination method's page-size check is the one piece of eager work. Everything after it is deferred: the iterator body does not run until a foreach pulls it, and a LINQ query composes lazily rather than materializing a list.
One closed TariffRule hierarchy, read by a switch and by a compiler
A closed rule hierarchy with a fixed set of cases is read two ways. A recursive switch expression walks it directly, the pattern-matching alternative to a classic visitor, while a separate compiler walks the same hierarchy once into a reusable delegate.
Same tree, two readings, one assertion that they agree
A single rule tree is read two ways against the same shipment: a recursive switch expression walks it directly, and a compiled delegate built from the same tree is invoked instead. A test asserts that both readings produce exactly the same result.
Save into a memento, push it, pop it, Restore from the copy
An originator captures its state into a new memento. A caretaker pushes it onto a stack without looking inside, and pops the most recent one to restore from. Restoring rebuilds its own copy rather than aliasing the memento's list.
An unowned sealed type, decorated from the outside
A sealed vendor type exposes only a constructor and read-only properties, standing in for third-party code examples cannot modify. An extension class attaches every needed behavior from outside that file, instance members, static members, and even an operator, without the vendor type ever changing.
An extension class declares static members inside a C# 14 extension block alongside an instance member written with the classic extension-method syntax C# has always had. Both forms resolve onto the same target type at a call site, coexisting in one static class.
Decorating a type you cannot modify, without mutating it
A vendor type's fields never move once constructed, standing in for third-party code examples cannot change. An extension class attaches read-only members, static members needing no instance, and an operator from outside that boundary. One method returns a brand-new instance rather than mutating the original.
One rule authored as data, read two different ways
A pricing rule is captured as a tree of expression nodes rather than compiled code. A visitor walks that tree and renders it as a string without ever running it, while compiling the same tree produces a delegate, the form that actually executes the rule.
Visiting without evaluating, and splicing without mutating
One visitor records which properties a rule touches without evaluating the tree. Another scales every constant by a factor, returning a new tree since expression trees are immutable. A third rebinds one rule's parameter onto another's and joins both bodies into one lambda.
Reading a rule without running it, compiling one that does
The same expression-tree rule appears on both sides of this figure. A visitor records which properties the rule touches without compiling or invoking it. Compiling the identical tree instead produces a delegate that executes the rule once invoked.
Dispatch through the type parameter, no instance required
An interface declares static abstract members that several concrete shipment types each implement. A generic method constrained to that interface calls the static member through its type parameter and reaches whichever concrete type the caller supplied, entirely without constructing an instance.
One Sum body over a custom type and a built-in one
A money type implements the numeric operator interfaces from the base class library. A generic summing method constrained to those interfaces seeds its total from the additive identity, the same body working for both the money type and a built-in decimal.
Three static contracts, one generic quote, one generic total
Three concrete shipment types each implement their own static base rate and rating formula. A generic method calls the static member for whichever type the caller passes, and the resulting quotes feed a generic summing method into one aggregate total.
A manifest file lists carrier rows. An incremental generator reads it at build time and emits one adapter per row, plus a generated registry, replacing a hand-written one that would otherwise scan loaded assemblies at startup.
Parsing to an equatable model so unchanged input is cached
An incremental pipeline turns a manifest file into an equatable model wrapping its parsed entries, then merges every parsed manifest into one model before emitting output. Because that model compares by value, an unchanged manifest produces an unchanged model and the pipeline skips emission entirely.
A generator builds a registry from a manifest at compile time, referencing each adapter it emits directly, so a dispatcher resolves a carrier from source references alone. The alternative scans loaded assemblies at startup, a path trimming can break and AOT does not fully support.
Flagging decimal money on a wire contract at compile time
An analyzer inspects every type carrying a wire-contract attribute during compilation. Types that model money as integer minor units pass, and types without the attribute are never examined. A wire-contract type with a decimal money property gets a build-time warning at that property's location.
An analyzer registers a compilation-start action that resolves a marker attribute and returns early if it is missing. Once resolved, it registers a symbol action for every named type, checking for the attribute and walking members for a decimal property to report a diagnostic on.
CarrierGatewayOptions binds once from configuration, then reaches callers three ways: a long-lived singleton value, a per-request snapshot, and a monitor that tracks the current value across reloads.
A reload reaches the monitor and startup gates on validation
When configuration reloads, CarrierGatewayOptions rebinds and RetryBudgetWatcher is notified immediately. A validator wired in at startup fails the host before any of this runs against bad config.
Collecting every failure before the host ever starts
CarrierGatewayOptionsValidator collects every failure reason instead of stopping at the first one, then ValidateOnStart fails the host at startup, before any caller can use the bad configuration.
The same parse-and-validate decision appears twice: Try-Parse style methods report failure through a boolean, while Result wraps the same outcome as a value a caller cannot ignore.
Branch immediately, or carry the reason and compose
A boolean and an out parameter force a caller to branch right away. A Result value carries its own failure reason and keeps composing through later steps. Neither shape wins outright.
Chaining through a failure reason, or branching by hand
Result's Map method chains a success through each step and short-circuits on the first failure, while the bool-and-out shape forces a caller to branch immediately after every call.
ICarrierGateway's async surface follows TAP conventions
ICarrierGateway follows the Task-based Asynchronous Pattern: every async member ends in Async, returns a Task or ValueTask, and accepts a cancellation token, so a fake implementation can stand in cleanly.
Cancellation and progress inside one dispatch loop
Dispatching a batch checks for cancellation before each item and reports progress after it, so a caller watching the progress consumer sees steady updates until a cancellation stops the loop.
A Task for real work, a ValueTask for the fast path
DispatchAsync returns a Task because it awaits real work, while IsReachableAsync returns an already-completed ValueTask on its usual synchronous path, avoiding an allocation for work that never went async.
One frozen lookup replaces a class-per-case hierarchy
DocumentDispatcher.Render looks up a DocumentKind in a FrozenDictionary built once at startup and calls the matching renderer directly, with no per-kind subclass or switch to maintain.
The same five document kinds can route through one frozen lookup table or through an interface with a class per kind and a factory. The table wins when the variation is pure data.
A frozen table built once, shared by every dispatcher
A seed dictionary of document kinds to renderer methods is frozen once into the shared Handlers table, and every DocumentDispatcher instance reads that one table instead of rebuilding its own copy.
A four-type component tower with a factory and an interface computes the same freight quote as one static method. Both take the same RateRequest and return the identical result.
Seven cooperating types fold into a three-line static method once the Strategy and Factory machinery is removed, because this scenario has never needed a second rating scheme.
One review question collapses the AI-generated tower
Asked for a freight-rate calculator, an AI assistant drafts the full Strategy and Factory tower. A review asks what the second rating scheme is, finds none, and collapses it to RateCalculator.Quote's three-line static method.
A sealed RateEngine with its dependencies built inside offers no way in. Adding a constructor and a protected override opens a seam where tests and other behavior can substitute collaborators.
Constructor injection, wrapping an ambient clock, a protected override hook, and an internal-only entry point open four different seams in the same RateEngine, each suited to a different kind of dependency.
A rate engine with an audit log, a tariff table, an identifier generator, and a clock all created inside itself is rebuilt so each becomes an injected collaborator the engine can substitute.
Six classic dependency-breaking techniques from Michael Feathers reshape the same rate engine, replacing inline construction and ambient calls with injected interfaces and a narrow internal seam.
A test substitutes four injected collaborators, including IAuditLog, then verifies audit.Received(1).Record(...), the interaction the legacy version hid inside a private list.
A sealed legacy rate engine gains a Feathers seam, then a Fowler refactor reshapes its structure. The two catalogues combine: opening a seam and improving the design are different problems, solved behind the same passing tests.
Feathers techniques open seams so the untested engine can be exercised under test, then Fowler techniques, including Extract Method and Replace Conditional with Polymorphism, reshape its structure while every test keeps passing.
A shared request and fixed clock feed both SeamedRateEngine and RateEngine; a theory test asserts the two engines produce the identical amount, proving the refactor changed the engine's shape, not its behavior.
The legacy engine has no stable seam to build on, but IRateEngine gives both a refactored and a rewritten replacement a shared contract, so QuoteService can swap one implementation for the other with no change of its own.
Test coverage, change frequency, blast radius, and domain stability each weigh toward refactoring in place or rewriting clean. The matrix is a judgement aid, not a formula that hands back a verdict.
Two engines sit behind one IRateEngine contract and, fed the same request and clock, return record-equal quotes. QuoteService swaps between them with a one-line change at the construction site.
ShipmentPipeline.Run carries a BookingRequest through rating, stowage, clearance, and invoicing in order. A rejected ClearanceResult halts the run before InvoiceStage, so no Invoice is produced.
RatingStage picks an IRatingStrategy through RatingStrategies.For, ClearanceStage returns a ClearanceResult, and InvoiceStage builds with InvoiceBuilder. StowageStage needs none of it.
A cleared booking runs through InvoiceStage to a finished Invoice. A rejected one, with ClearanceResult.Cleared false, stops at ClearanceStage and never reaches invoicing.
An assistant proposes pattern-shaped code, the SHIP0002 analyzer flags a single-implementation Strategy, and a human decides whether to collapse the abstraction or justify it before the change merges.
An IRatingStrategy with only StandardRatingStrategy behind it trips SHIP0002. Adding ExpressRatingStrategy gives the interface a genuine second shape, and the analyzer falls silent.
AnalyzerTestHarness compiles a snippet and runs the analyzer between compilation and its diagnostics. A single-implementation Strategy makes SHIP0002 fire; a two-implementation one leaves it quiet.
Thousands of suspended bookings, a handful of threads
SailingBookingDesk lets thousands of bookings await IBookingLedger.ConfirmAsync at once, each suspended as a small heap state object. A handful of pooled threads serve every suspended booking, not one thread per booking.
Stackful threads prototyped, stackless state machines shipped
The .NET team prototyped stackful green threads, where every booking reserves a full call stack that grows with concurrency. They shipped stackless state machines instead, where a suspended await costs a small heap allocation and the thread returns to the pool.
A thousand BookingRequest calls start from one calling thread and park at the ledger await with zero threads held. A single release then drains every suspended booking through one Task.WhenAll.
Many callers reach LazyTariffProvider.Value at once, but the ExecutionAndPublication mode guarantees the underlying builder runs exactly once. Every caller is handed the same TariffTable instance.
Three modern idioms each build a TariffTable exactly once: Lazy initialization, a lock-guarded field, and a static type initializer. Double-checked locking, the historical form they replace, is shown as superseded.
LazyTariffProvider caches a failed build and rethrows the exact same exception to every later caller, instead of retrying. The test asserts the first and second failures are the same instance.
Four coordination strategies wrap one shared servant
SynchronizedStowagePlan locks synchronously, awaiting inside that lock fails to compile, SemaphoreStowagePlan awaits inside an async gate, and StowageActiveObject replaces the gate with a bounded queue that serializes access to the same servant.
Six Active Object participants, mapped onto real code
Proxy is ReserveAsync, Activation List is the bounded channel, and Servant is StowagePlan. Scheduler and Future are grayed out because they are no longer hand-written types: they dissolved into await foreach and the language's own task.
A full one-slot channel blocks a third reservation until release
A one-slot channel fills with B while A's write holds a gated ledger open. A third reservation's write waits until release lets the queue drain, completing C's task.
Many producers, one bounded channel, many consumers draining it
Several producers write HandlingEvent values into one bounded channel while several consumers drain it concurrently. A full channel slows the producers, and completing the writer once stops every consumer after the last event.
A known count drains to exactly one record per event
Submitting a known number of events, completing the writer, and waiting for every consumer task to finish proves each event is recorded exactly once; a single producer's order survives a single consumer because the channel is first in, first out.
Receive, validate, and record chained over bounded channels
Receive, validate, and record each run as their own producer and consumer pair, linked by bounded channels. When validate slows down, its full channel propagates backpressure upstream to receive.
A fixed-size connection pool and a scratch buffer pool, side by side
GatewayConnectionPool hands connections to renters and takes them back on return, parking a renter when the pool runs out. ManifestWriter rents and returns a scratch buffer from an array pool the same way.
A full connection pool parks a third rent until one returns
A two-connection GatewayConnectionPool with both connections rented leaves a third RentAsync call incomplete. Returning one connection completes that pending rent with the exact connection that came back.
Reusing a rented buffer instead of allocating a fresh array every time
Renting a buffer, using it, and returning it cleared means the next rent gets back the same array. Allocating a fresh array on every call instead produces garbage with nothing to reuse.
Four classic patterns meet concurrency around one immutable event
Four classic patterns, observer, iterator, decorator, and command, adapt to concurrency by working from one immutable HandlingEvent that every caller can share safely.
One immutable snapshot keeps a running notification safe from a concurrent change
HandlingEventHub captures one immutable snapshot of subscribers before Raise iterates it, while a concurrent subscribe or unsubscribe swaps in a new snapshot without disturbing the notification already in flight.
Producers publish into one feed that a consumer drains until it ends
Producers publish HandlingEvent values into HandlingEventFeed while a consumer drains it with an await foreach loop. Calling Complete ends the sequence cleanly, and cancelling the token ends it early.