Pattern or no pattern?
What you will learn on this page
Section titled “What you will learn on this page”- How to decide between a design pattern and a simpler form (a function,
an
enum classand aswitch, astd::variant, a lambda) from the forces in a problem, instead of from the pattern’s name. - How to say what would change your mind: which new fact in the requirements would make the other design the better one.
- How to count what a pattern costs in a particular place: extra types and files, indirection, and questions about who owns what and for how long.
- How to judge your own answer when two designs are both defensible.
How to use this page
Section titled “How to use this page”There are eight situations below, from eight different small programs. Each is a paragraph long, and each gives the facts that matter: how many variants there are, how often they change, who adds them, what the tests need, and any limits on performance or lifetime. They are deliberately mixed. For some, the best answer is no pattern at all; for some, a particular pattern clearly earns its place; and for some, two designs are both reasonable and the answer says so.
For each situation:
- Read it, and stop. Write down, in a few lines, what you would build and what would change your mind. Name the facts in the paragraph that decided it for you.
- Open “Show the explained answer” and compare. Each answer gives a recommended design and why, at least one alternative and when it would be better, the signal that would flip the decision, and what the pattern would cost here.
- Judge your answer by its reasons, not by its label. An answer that names the same pattern as ours for a different reason has not found the force. An answer that picks the other design, and names the fact that would have to be true for it to win, is a good answer.
A pattern’s name is never the whole answer. “Use Strategy” leaves open what the interface is, who creates the objects, who owns them, and how they are tested. The answers below say those things too, and so should yours.
Two questions from the patterns section do most of the work. From Pattern, or a simple function: what does the pattern give this problem that the simple form does not? From When patterns hurt: which force in these requirements does the pattern resolve? If you cannot answer the second one, the pattern is speculative generality.
The C++ sketches in the answers are short and illustrative. Each was checked to compile with GCC and Clang, with the includes and declarations it assumes added; none was run.
The situations
Section titled “The situations”Exercise: A recipe app's weight units
A recipe app scales recipes and shows ingredient weights in the reader’s
chosen unit: grams, kilograms, ounces, or pounds. The list of units has
not changed in two years, and one developer maintains the app. A
colleague proposes a UnitConverter interface with one class per unit,
created by a UnitFactory from the unit’s name, “so that new units are
easy to add”. Tests must check, for example, that one pound is shown as
453.59 grams.
What would you do, and what would change your mind?
Show the explained answer
Recommended: no pattern. An enum class Unit and one function that
converts.
IllustrativeA fragment for explanation; not compiled on its own.
enum class Unit { gram, kilogram, ounce, pound };
// Grams in one of each unit. No default: -Wswitch warns if a unit is// added to the enum and forgotten here.constexpr double grams_per(Unit unit) { switch (unit) { case Unit::gram: return 1.0; case Unit::kilogram: return 1000.0; case Unit::ounce: return 28.349523125; case Unit::pound: return 453.59237; } return 0.0; // not reached for a valid Unit}
constexpr double convert(double amount, Unit from, Unit to) { return amount * grams_per(from) / grams_per(to);}Why, from the forces. There are four units, the list is stable, and
one person changes it. More important, the units do not differ in
behaviour: each one is a single number, grams per unit. A difference
that is a number is data, and data belongs in a table or a switch, not
in a class each. The tests are plain calls with values, such as
convert(1.0, Unit::pound, Unit::gram), with no objects to set up.
An alternative, and when it is better. A constexpr array of factors
indexed by the unit is just as good, and shorter if the list grows to a
dozen. A map from a unit’s name to its factor, loaded from a file, is
better as soon as users can define units, because then the set is
not known when the program is written. Neither is a pattern.
What would flip the decision. Two different signals point to two different designs:
- “Show cups and tablespoons too.” A cup of flour and a cup of sugar weigh different amounts, so a volume conversion needs the ingredient’s density. That is more data (a density per ingredient) and an extra parameter, still not a pattern.
- “Each unit has its own parsing, rounding, and display rules, such as
‘1 lb 3 oz’, and units come from regional add-ons written by other
people.” Now each unit has several behaviours that are code, not
numbers, and the set is open. A
UnitConverterinterface would earn its place (Strategy, when to use it).
What the pattern would cost here. Four classes, an interface, and a
factory, perhaps six files, to hold four numbers. Each caller must get a
converter from the factory and decide who owns it (a std::unique_ptr
returned by the factory, or a reference to an object stored somewhere).
A misspelled unit name becomes a run-time failure in the factory instead
of a compile error on an enumerator. This is question 5 of
the six questions
(a fixed set of kinds, each of them data) in a very small form: each
kind is so little data that an enumerator and a number replace even the
variant.
Exercise: Two badge scanners at a conference
A conference app counts attendance at session doors. Each door has a
handheld badge scanner, and the organisers rent scanners from one of two
vendors, depending on the venue. Each vendor ships its own C library:
vendor A has va_open, va_read (which waits for a code with a timeout
and returns a status number), and va_close; vendor B calls a function
you register, from its own thread, whenever a badge is read. Which vendor
is used is set in the venue’s configuration file. The counting rules (no
double counting, a badge for the wrong session is refused) must be tested
on a laptop with no scanner attached. A third vendor might appear in a
few years.
What would you do, and what would change your mind?
Show the explained answer
Recommended: Adapter. A small interface in the app’s own terms, one adapter per vendor library, and a fake for the tests.
IllustrativeA fragment for explanation; not compiled on its own.
// The app's own interface, in the app's own types: the attendance logic// needs nothing else from a scanner.class BadgeReader {public: virtual ~BadgeReader() = default; // The next badge code, or nothing if no badge was scanned in time. virtual std::optional<std::string> next_badge(std::chrono::milliseconds wait) = 0;};
// One adapter per vendor SDK. It owns the SDK's device handle, so it can// be neither copied nor moved; the program holds it in a unique_ptr.class VendorAReader final : public BadgeReader {public: explicit VendorAReader(const std::string& port) : device_{va_open(port.c_str())} { if (device_ == nullptr) throw std::runtime_error{"no scanner on " + port}; } ~VendorAReader() override { va_close(device_); } VendorAReader(const VendorAReader&) = delete; VendorAReader& operator=(const VendorAReader&) = delete;
std::optional<std::string> next_badge(std::chrono::milliseconds wait) override { std::array<char, 64> buffer{}; // Vendor A: 0 = read (text ends with '\0'), 1 = timeout, below 0 = error. const int status = va_read(device_, buffer.data(), static_cast<int>(buffer.size()), static_cast<int>(wait.count())); if (status == 1) return std::nullopt; if (status < 0) throw std::runtime_error{"scanner error " + std::to_string(status)}; return std::string{buffer.data()}; }
private: va_device* device_;};Why, from the forces. Three forces are present at once, and the interface resolves all of them. There are two real implementations, chosen at run time from configuration. The libraries are code you cannot change, with interfaces that do not match each other or the app (status numbers, raw handles, a callback on a foreign thread). And the tests need a fake that returns badge codes from a list. This is the boundary case of When patterns hurt: an abstraction at the edge of the program, with more than one implementation today.
Naming the pattern is the easy part. The design decisions are:
- The interface is the app’s, not a vendor’s.
next_badgereturns astd::optional<std::string>; the counting logic never sees a status number or a handle. Vendor B’s adapter turns its callbacks into the same call, by putting each code in a queue protected by a mutex thatnext_badgereads with a timeout. - Each adapter owns its device. It opens the device in its
constructor and closes it in its destructor, and it is neither
copyable nor movable: vendor B’s library keeps a pointer to the
adapter for its callback, so the adapter must stay at one address, and
the callback must be unregistered in the destructor before the queue is
destroyed. The program holds the chosen adapter in a
std::unique_ptr<BadgeReader>, created by one factory function that reads the configuration.
An alternative, and when it is better. If the counting logic only
ever needs “the next code”, a std::function<std::optional<std::string>()>
parameter could replace the interface, with the adapters still owning
the devices. That is lighter when there is exactly one operation; an
interface is clearer once there are two or three (a battery level, a
beep on refusal).
What would flip the decision. “We bought our own scanners, all from vendor A, and the tests will run against the vendor’s simulator.” With one library and no need for a fake, the virtual interface has nothing to choose between. Keep a small RAII wrapper class that owns the handle and translates errors, and drop the interface.
What the pattern costs here. An interface, two adapter classes, a fake, and a factory function; a virtual call per read, which is nothing next to waiting for a person to scan a badge; and the lifetime rules above, which are the real work. See Adapter: ownership and lifetime.
Exercise: Undo in a pixel-art editor
A small pixel-art editor edits one image at a time, at most 128 by 128 pixels, 4 bytes per pixel. It has seven tools: pencil, line, rectangle, flood fill, “replace colour” (every pixel of one colour becomes another), flip, and resize canvas. Users want 200 steps of undo and redo, and an Undo menu that says what it will undo (“Undo flood fill”). About two new tools are added each year by the same two developers. There are no plans for macros, scripting, or shared editing.
What would you do, and what would change your mind?
Show the explained answer
Two answers are defensible here. Our default is the simpler one, snapshots of the whole canvas, but Command with an undo per tool is a good answer too, and the criteria below say when it is the better one.
Snapshots. The canvas is a value (a width, a height, and a vector of pixels), so a copy of it is a complete record of a step. Before each tool runs, the editor stores a copy with a label.
IllustrativeA fragment for explanation; not compiled on its own.
struct Canvas { int width = 0; int height = 0; std::vector<std::uint32_t> pixels; // width * height colours, row by row};
struct Snapshot { std::string label; // such as "flood fill", for the Undo menu Canvas before; // a full copy: the canvas is a value};
// Undo by snapshots: every tool is undoable, and no tool writes undo code.class History {public: // Called by the editor before a tool changes the canvas. void record(std::string label, const Canvas& before) { if (steps_.size() == max_steps) steps_.pop_front(); steps_.push_back({std::move(label), before}); } // Puts back the canvas from before the last step; false if there is none. bool undo(Canvas& canvas) { if (steps_.empty()) return false; canvas = std::move(steps_.back().before); steps_.pop_back(); return true; }
private: static constexpr std::size_t max_steps = 200; std::deque<Snapshot> steps_;};Redo works the same way, with a second list. The arithmetic is in its
favour: one snapshot is at most 128 × 128 × 4 = 65,536 bytes (64 KiB),
and 200 of them are at most 12.5 MiB. Every tool, including flood fill
and “replace colour”, which are awkward to reverse, is undoable with no
undo code in the tool, so a new tool cannot have a wrong undo. Because
Canvas is an ordinary value type owned by the editor, this does not
need the full Memento structure, whose point is
to save an object’s state without exposing its private parts.
Command. Each tool becomes a command object with apply and undo,
and the history is a std::vector<std::unique_ptr<Command>>. Memory per
step is small (a pencil stroke stores the pixels it changed and their old
colours), and each command knows its own label. But each of the seven
tools, and every future one, must write a correct undo, and the tools
that change many pixels must save what they overwrite anyway.
How to judge your own answer. Either answer is good if it is justified by these facts:
| If this is true | It favours |
|---|---|
| The whole state is small, so depth × size fits the memory budget | snapshots |
| Many tools change many pixels, or are hard to reverse | snapshots |
| The state is large and each step changes a small part | Command |
| Steps must be replayed, recorded as macros, or sent to another user | Command |
| Each step must be described or inspected, not just reversed | Command (snapshots need a label) |
The comparison in Memento or Command? covers the same trade-off, and the two combine well: a command that is hard to reverse can keep a snapshot of what it changed.
What would flip the decision. “Layers, and canvases up to 4096 by 4096.” One layer is then 64 MiB, and 200 snapshots do not fit. Move to Command, or to snapshots of only the changed tiles of the image. “Record a macro and replay it on other images” also points to Command, because a snapshot cannot be replayed on a different image.
What each costs. Snapshots cost memory and a copy per step (a 64 KiB
copy is quick next to a person’s click). Command costs a class per tool,
an undo per class that must be tested in both directions, and a
history of owning pointers.
Exercise: Progress for a long file copy
A backup tool copies large files. The command-line version shows a
progress bar in the terminal during each copy; a desktop version, planned
for next year, will show a progress dialog. In both, exactly one caller
wants progress for the one copy it started, while the copy runs, on the
same thread. A teammate proposes making the copier a subject, with
subscribe and unsubscribe and a ProgressListener interface. Tests
must check that the reported progress reaches the file’s full size.
What would you do, and what would change your mind?
Show the explained answer
Recommended: no pattern. A callback parameter, passed a lambda.
IllustrativeA fragment for explanation; not compiled on its own.
struct Progress { std::uint64_t bytes_done = 0; std::uint64_t bytes_total = 0;};
// Copies the file, calling on_progress after each block. The callback is// used only during this call and never stored, so a lambda may capture// the caller's locals by reference.bool copy_file(const std::filesystem::path& from, const std::filesystem::path& to, const std::function<void(const Progress&)>& on_progress);
void copy_with_bar(const std::filesystem::path& from, const std::filesystem::path& to, ProgressBar& bar) { const bool copied = copy_file(from, to, [&bar](const Progress& progress) { bar.show(progress.bytes_done, progress.bytes_total); }); bar.finish(copied);}Why, from the forces. There is one listener, it is chosen by the
caller, and it is needed only during the call. That is question 1 of
the six questions:
the part that varies is one call, chosen by the caller. The desktop
version is a different caller with a different lambda; the copier does
not change. The lifetime is simple to state: the callback is used only
inside copy_file and never stored, so capturing bar by reference is
safe. A test passes a lambda that appends each Progress to a local
vector and then checks the last entry, with no listener class.
An alternative, and when it is better. A template parameter instead
of std::function avoids an indirect call per block, which does not
matter next to disk input and output; it is worth it only in a hot loop.
If the user must be able to cancel, the callback can return a value that
says whether to go on; that is still a callback, not a pattern.
What would flip the decision. “Several parts of the program must react to every copy (a log, a tray icon, a statistics page), they are added and removed while the program runs, and the copier must not know about them.” That is the force Observer resolves: a subject that must not depend on listeners which come and go (Observer: when to use it). If the copy also moves to a worker thread, the callback must not touch the user interface directly in either design; the result has to be passed to the interface’s thread.
What the pattern would cost here. An interface, a listener class per caller, and a list of subscribers inside the copier; and the lifetime question that a parameter does not have: a listener destroyed while still subscribed leaves a dangling pointer, which is why the Observer page needs subscription handles (the naive version and its two lifetime bugs). With one listener, used for one call, all of that buys nothing. This is section 6 of Pattern, or a simple function with a callback in place of a returned value.
Exercise: A garage door controller
A garage door controller runs on a small board. The door is closed, open, moving (up or down), stopped part-way, or in a fault. Six events arrive: the button, the top and bottom limit switches, the obstacle sensor, a motor over-current signal, and a timer tick. While moving, the door has a deadline: if the limit switch is not reached within 15 seconds, the controller stops the motor and records a fault. When stopped part-way, the next press goes the opposite way to the last movement. A fault holds an error code, shown on a small display, and only a reset clears it. An obstacle while closing reverses the door. The team wants each safety rule tested, and wants to review the rules state by state.
What would you do, and what would change your mind?
Show the explained answer
Recommended: State. Our suggested form is the std::variant one: a
struct per state that holds only that state’s data, and a function per
event that returns the next state.
IllustrativeA fragment for explanation; not compiled on its own.
// Clock is std::chrono::steady_clock; travel_limit is 15 seconds;// opposite() swaps up and down; overloaded is the helper from the// floor-plan answer below.enum class Direction { up, down };
// One struct per state; each holds only the data that state needs.struct Closed {};struct Open {};struct Moving { Direction direction; Clock::time_point deadline; // a fault if the limit switch is not reached by then};struct Stopped { Direction was_moving; // the next press goes the other way};struct Fault { int code; // shown on the panel; only a reset clears it};using DoorState = std::variant<Closed, Open, Moving, Stopped, Fault>;
// One function per event. A Closed door cannot have a deadline or an// error code, because those members do not exist in Closed.DoorState on_button(const DoorState& state, Clock::time_point now) { return std::visit( overloaded{ [&](const Closed&) -> DoorState { return Moving{Direction::up, now + travel_limit}; }, [&](const Open&) -> DoorState { return Moving{Direction::down, now + travel_limit}; }, [](const Moving& moving) -> DoorState { return Stopped{moving.direction}; }, [&](const Stopped& stopped) -> DoorState { return Moving{opposite(stopped.was_moving), now + travel_limit}; }, [](const Fault& fault) -> DoorState { return fault; }, }, state);}Why, from the forces. The states have data of their own: a
direction and a deadline while moving, the last direction when stopped,
an error code in a fault. With one enum class and a struct of all
those members, a closed door could have a deadline and an error code,
and every rule would have to remember which members mean something in
which state. Question 4 of
the six questions
asks whether the stages have no data of their own; here they do. There
are five states and six events, and the rules are safety rules, so
making impossible states impossible to write is worth some structure.
The tests are plain: build a state, call an event function with a fixed
time, and check the state that comes back. No clock or allocation is
needed.
An alternative, and when it is better. The classic form, an object per state with a virtual function per event, keeps each state’s rules together in one class, which matches “review the rules state by state”. It costs a virtual call and, usually, an allocation per transition, which a small board may not allow. The variant form keeps one event’s rules together instead, across all states. Both are State; State: how to choose compares them. If review by state matters more than avoiding allocation, choose the classic form, or keep the variant and put each state’s handlers in its own struct.
What would flip the decision. “The door only needs open and closed,
with a button.” Two states with no data are an enum class and a
function; State would be ceremony. In the other direction, if each state
grows long rules of its own (a learning mode, a holiday lock, a remote
control), the classic form’s one class per state becomes easier to read.
What the pattern costs here. Five structs and a variant instead of an
enum, an overload set in every event function, and compiler errors
from std::visit that are long to read. A new state needs a struct and
a lambda in each event function (a missing one is a compile error, which
here is what you want).
Exercise: Tiles in a puzzle game
A two-dimensional puzzle game loads each level from a text file, one
character per tile: # wall, . floor, D door, K key, W water,
S start. There are about six kinds of tile now; the level designers ask
for a new one about once a month (ice, a conveyor belt, a pressure
plate), and the two programmers add it to the game each time. Tiles
differ in what happens when the player steps on them: a door needs a
key, water blocks the player unless they have boots, ice slides them on.
A level has up to 10,000 tiles, and restarting a level copies it.
What would you do, and what would change your mind?
Show the explained answer
Two answers are defensible here. One is a std::variant of small
tile structs with a single parsing function; the other is a Tile
interface with a class per tile, created through a registry of makers
keyed by character. Our default for the facts given is the variant.
IllustrativeA fragment for explanation; not compiled on its own.
struct Floor {};struct Wall {};struct Door { bool locked = true;};struct Key {};struct Water {};using Tile = std::variant<Floor, Wall, Door, Key, Water>;
// The one place that knows the level-file characters. 'S' marks the start;// the loader records its position, and the tile itself is floor.std::optional<Tile> parse_tile(char symbol) { switch (symbol) { case '.': case 'S': return Floor{}; case '#': return Wall{}; case 'D': return Door{}; case 'K': return Key{}; case 'W': return Water{}; default: return std::nullopt; // the loader reports the line and column }}For the variant. The people who add tiles are the programmers, in
the same code base, so the set of kinds is not open to outsiders. Most
tiles have a line or two of behaviour. A level is a
std::vector<Tile> of plain values: copying it on restart is one copy,
with no allocation per tile, and the tiles sit next to each other in
memory. parse_tile is a factory function, which is often all a
“factory” needs to be
(Factory Method: choosing a form).
When a tile is added, every std::visit that misses it fails to compile,
which finds the places to change, as long as no visitor has a catch-all
auto overload that quietly accepts the new tile.
For the interface and registry. Each tile’s behaviour lives in its own class, so adding ice means one new file and one registration line, and the step logic, drawing, and sound for ice are together. That is better when tiles have long rules or their own changing state (a conveyor’s direction and timer).
How to judge your own answer. Ask:
- Who adds tiles? Programmers in this code base favour the variant. Players or modders, through plug-ins or scripts, need the interface and a registry, because the variant cannot be extended from outside.
- How much behaviour per tile, and in how many places? A few lines, in two or three functions, favour the variant. Long rules, own state, and a growing number of operations per tile favour a class per tile.
- What does copying and storage cost? With an interface, a level is a
std::vector<std::unique_ptr<Tile>>: one allocation per tile, and a restart needs aclone()per tile. With 10,000 tiles that is still modest, but it is a cost the variant does not have.
What would flip the decision. “Players can make their own levels with their own tiles, loaded from mods.” The set of kinds is then open, and the interface with a registry earns its place, even with the costs below.
What each costs. The variant puts one tile’s behaviour in several functions, so a tile with long rules is hard to read in one place. The registry adds an interface, a class per tile, owning pointers, and a registration step; a tile that was never registered fails when a level is loaded (an unknown character), not when the program is compiled. Registry of makers shows the form and its ownership.
Exercise: Shapes in a floor-planning tool
A furniture shop’s floor-planning tool lets a customer draw a room from
rectangles, circles, and L-shapes. These three kinds have been the same
since the first release, and the shop has no plans for more. What keeps
changing is what the tool does with them: area came first, then the
perimeter (for skirting boards), this month a bounding box for collision
checks, and next an export to SVG. One team owns all the code. The undo
feature keeps copies of the whole plan. Two proposals: a Shape base
class with a virtual function per operation, or the classic Visitor
pattern.
What would you do, and what would change your mind?
Show the explained answer
Recommended: no class pattern. A std::variant of plain structs, with
each operation a free function that uses std::visit.
IllustrativeA fragment for explanation; not compiled on its own.
struct Rect { double width; double height;};struct Circle { double radius;};struct LShape { // a rectangle with a rectangular corner cut out double width; double height; double cut_width; double cut_height;};using Shape = std::variant<Rect, Circle, LShape>; // plain values: copying is free
template <class... Fs>struct overloaded : Fs... { using Fs::operator()...;};template <class... Fs>overloaded(Fs...) -> overloaded<Fs...>; // optional in C++20; Clang 14 still needs it
// A new operation is one new function. If a shape kind is missing,// std::visit does not compile.double area(const Shape& shape) { return std::visit( overloaded{ [](const Rect& rect) { return rect.width * rect.height; }, [](const Circle& circle) { return std::numbers::pi * circle.radius * circle.radius; }, [](const LShape& ell) { return ell.width * ell.height - ell.cut_width * ell.cut_height; }, }, shape);}Why, from the forces. The set of kinds is fixed and controlled by
one team, and the set of operations grows. With a variant, a new
operation is one new function, and the compiler refuses a std::visit
that misses a kind. With a base class, each new operation is a new
virtual function and an override in every class. The shapes are data,
and the undo copies them often: a vector of variants copies with no
allocation per shape and no clone(). This is question 5 of
the six questions.
std::visit does the job the Visitor pattern was invented for (an
operation chosen by the kind of element), without the accept and
visit functions in every class
(Visitor: the std::variant form).
An alternative, and when it is better. A Shape base class is better
when kinds are added often and operations rarely: then each new kind
is one class, while with the variant it is a change to every operation.
The classic Visitor fits when the shapes already form a class hierarchy
with behaviour of their own and the operations are large enough to want a
class each (which form?).
What would flip the decision. “Shapes from a partner’s furniture
catalogue, as plug-ins.” The set of kinds is then open to code the team
does not own; the variant cannot be extended from outside, and a Shape
interface earns its place.
What a pattern would cost here. With a hierarchy: a class per shape,
a std::vector<std::unique_ptr<Shape>> for the plan, a clone() for
every undo copy, and an edit to every class for every new operation.
With the classic Visitor: on top of that, an accept per shape and a
visitor class per operation, two virtual calls per shape visited, and
results stored in the visitor instead of returned.
Exercise: Storage layers in a photo service
A photo-sharing service stores uploaded files through a small interface
with two functions, put(key, bytes) and get(key). Deployments differ.
The on-premises install encrypts files at rest and keeps an in-memory
cache. The cloud install retries calls that fail with a network error
and records timing metrics, but does not encrypt, because the storage
provider already does. Developers’ laptops use none of these. The
operations staff choose the layers in each deployment’s configuration
file, and compression is scheduled for next quarter. Each layer must be
tested on its own.
What would you do, and what would change your mind?
Show the explained answer
Recommended: Decorator. Each layer is a class that implements the
same two-function interface and owns the store it wraps; main builds
the chain once, from the configuration.
IllustrativeA fragment for explanation; not compiled on its own.
class BlobStore {public: virtual ~BlobStore() = default; virtual void put(const std::string& key, const Bytes& data) = 0; virtual std::optional<Bytes> get(const std::string& key) = 0;};
// One layer: retries a call that failed with a network error, then gives up.// It owns the store it wraps.class RetryingStore final : public BlobStore {public: RetryingStore(std::unique_ptr<BlobStore> inner, int attempts) : inner_{std::move(inner)}, attempts_{attempts} {}
void put(const std::string& key, const Bytes& data) override { with_retries([&] { inner_->put(key, data); }); } std::optional<Bytes> get(const std::string& key) override { std::optional<Bytes> result; with_retries([&] { result = inner_->get(key); }); return result; }
private: template <class Call> void with_retries(Call&& call) { for (int attempt = 1;; ++attempt) { try { call(); return; } catch (const NetworkError&) { if (attempt >= attempts_) throw; } } }
std::unique_ptr<BlobStore> inner_; int attempts_;};
// main builds the chain once, from the configuration. The last layer// created is the outermost, so it sees each call first.std::unique_ptr<BlobStore> make_store(const StoreConfig& config) { std::unique_ptr<BlobStore> store = make_base_store(config); if (config.encrypt) store = std::make_unique<EncryptingStore>(std::move(store), config.key); if (config.compress) store = std::make_unique<CompressingStore>(std::move(store)); if (config.retries > 0) store = std::make_unique<RetryingStore>(std::move(store), config.retries + 1); return store;}Why, from the forces. The layers combine differently in each deployment, the combination is chosen when the program starts, the interface is narrow (two functions, so a layer has little forwarding to do), each layer must be tested alone (wrap a fake store that records calls), and a new layer is already scheduled, which is one of the cases in when up-front structure is justified.
Choosing Decorator leaves two decisions that the name does not make:
- Order is part of the design. Compression must happen before
encryption, because encrypted data looks random and does not compress.
Since the outermost layer sees a
putfirst, the compressing layer must wrap the encrypting one, as inmake_store. The cache’s place matters too: above the retry layer, a cache hit never touches the network. - Ownership is a chain. Each layer owns the next through a
std::unique_ptr, and the caller owns only the outermost. Destroying it destroys the chain from the outside in.
An alternative, and when it is better. One Store class with flags
(encrypt, cache, retry) and if statements in put and get is
simpler when there are two layers and the order never changes, and
easier to step through in a debugger. It gets worse with each layer,
because every combination runs through the same two functions, and
testing one layer alone means turning the others off.
What would flip the decision. “Every deployment uses the same layers in the same order”: then a single function that does the steps in order is clearer (Decorator: when not to use it). “The interface grows to listing, deleting, metadata, and multi-part uploads”: with ten functions, each decorator is mostly forwarding code, and a forgotten one silently skips the layer; narrow the interface first, or decorate only the part that needs layers.
What the pattern costs here. A class per layer, an order that is easy to get wrong and must be tested as a whole, a call that passes through several objects in a debugger, and an error from the innermost store that each layer must pass on correctly.
Check yourself
Section titled “Check yourself”After the eight situations, go through this list. Each point is a habit the answers rely on; if you missed one more than once, reread the lesson linked.
- I named the force behind every pattern I chose (a set of kinds open to others, several implementations chosen at run time, states with their own data, layers that combine) and found it in the paragraph, not in my expectations (question each pattern).
- When I chose no pattern, I named the simple form and the fact that makes it enough (a difference that is only data, one listener for one call, a fixed set of kinds).
- For every answer, I wrote what would change my mind: a concrete new requirement, not “if it gets more complex”.
- I said who owns each object I introduced, how long it lives, and what happens to callbacks or pointers when it is destroyed.
- I counted the pattern’s cost in this program: types, files, indirection, allocation, and the tests it needs.
- For the two judgement calls, I gave the criteria that decide them rather than only a preference, and I could argue for the other answer too.
- I did not stop at the pattern’s name: I said what the interface is, who creates the objects, and how they are tested.
This page is practice for your own judgement. It is not a test, and it does not certify anything.
Summary
Section titled “Summary”- Start from the forces in the requirements: how many variants, how often they change, who adds them, what tests need, and any limits on memory, allocation, or lifetime.
- A difference that is only data is a table or a
switch. One behaviour chosen by the caller is a lambda. A fixed set of kinds that are data is astd::variant. - A pattern earns its place when its force is present today: a boundary with code you cannot change, layers that combine at run time, states with their own data, or a set of kinds open to other people.
- Some decisions have two good answers. Say which facts would make each one better, and what new requirement would change your choice.