Skip to content

When patterns hurt

Difficulty: Intermediate

Key concepts

  • pattern overuse
  • shared mutable state
  • global state
  • forces
  • pure function
  • simplifying a design
  • How pattern overuse happens: a pattern is chosen because a word in the requirements matches its name, not because its problem is present.
  • What global and shared mutable state cost, shown with code and tests, and with sanitizer results from scratch programs: tests that depend on each other, data races, and code whose result depends on who else changed an object.
  • How to question each pattern in a design by asking which force it resolves, and how to simplify the design when the answer is “none”.
  • How to tell the abstraction that earns its place from the ones that do not, and which requirement changes would bring a removed pattern back.

A public library sends members a reminder the day before a book is due back. The program runs once each morning.

  1. FR-1 Email each member one reminder for each loan due back tomorrow, naming the book and the due date.
  2. FR-2 Report how many reminders this run sent, for the library’s daily log.
  3. FR-3 Tests check which reminders are sent without sending real email, and can run in any order.
  4. C-1 (constraint) The mail service is outside the program: a company’s mail system, reached through its own library.

That is the whole problem. Hold on to how small it is, because the first design below is not.

A developer who has just learned the patterns reads the requirements and finds a pattern for every phrase. Each choice sounds reasonable on its own:

Phrase in the requirements Pattern chosen What the phrase needed
“loans due back tomorrow”: a rule for choosing Strategy: SelectionStrategy, DueTomorrow one if; there is one rule
“a reminder naming the book and date”: an object Builder: ReminderBuilder a struct of two strings
“make a reminder” Factory: ReminderFactory::create_builder() nothing; the struct is built directly
“email each member”: something is notified Observer: ReminderListener, MailListener one call to the mail sender
“the reminder service”: one per program Singleton: ReminderService::instance() a function that main calls
“today’s date” and “how many”: data several need a shared context: std::shared_ptr<ReminderContext> a parameter and a return value
“the mail service is outside the program” an interface: MailSender this one is needed (C-1 and FR-3)

This is often called pattern soup: patterns used because they are known, not because their problems are present. Every pattern below is written correctly. None of them, except the last row, is needed.

The shared context holds today’s date and a running count:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.hpp
// Shared by every object below, and changed by some of them.
// Each holder keeps a std::shared_ptr to the same ReminderContext, so a
// change made through one holder is seen by all the others. `today` is
// read by the strategy to decide what is due; `sent` is a running total
// that the listener adds to on every reminder, across every run.
struct ReminderContext {
Date today;
int sent = 0;
};

The five patterns:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.hpp
// Strategy, with one strategy.
// An interface for "which loans get a reminder". It hurts because there is
// only one rule, so the interface and the virtual call buy nothing; a plain
// function would do.
class SelectionStrategy {
public:
virtual ~SelectionStrategy() = default;
// Returns copies of the loans it selects.
virtual std::vector<Loan> select(const std::vector<Loan>& loans) const = 0;
};
// The only strategy: loans due the day after context->today. It does not
// take today's date as an argument; it reads it from the shared context,
// so anyone else holding the context can change what select returns.
class DueTomorrow final : public SelectionStrategy {
public:
explicit DueTomorrow(std::shared_ptr<ReminderContext> context);
// `const` promises not to change the strategy, but the context it
// points at is not const and can change at any time.
std::vector<Loan> select(const std::vector<Loan>& loans) const override;
private:
std::shared_ptr<ReminderContext> context_; // one of four holders
};
// Builder, for a struct of two strings.
// Each setter stores one value and returns *this, so calls can be chained:
// builder.to(...).title(...).due(...).build(). A Reminder has just two
// fields, both always needed, so a brace initializer would build it in
// one line; the builder adds a class and a place to forget a field.
class ReminderBuilder final {
public:
ReminderBuilder& to(std::string email);
ReminderBuilder& title(std::string title);
ReminderBuilder& due(Date due);
// Makes the Reminder: the email, and the text "'title' is due back on
// YYYY-MM-DD".
Reminder build() const;
private:
std::string to_;
std::string title_;
Date due_{};
};
// Factory, for the one builder.
// create_builder only calls std::make_unique<ReminderBuilder>(). There is
// one kind of builder, so the factory hides no choice, and it puts each
// builder on the heap for no reason.
class ReminderFactory final {
public:
static std::unique_ptr<ReminderBuilder> create_builder();
};
// Observer, with one observer.
// Lets any number of listeners hear about each reminder. There is only one
// listener, fixed when the program starts, so the subscribe list adds
// lifetime problems (below) without adding a choice.
class ReminderListener {
public:
virtual ~ReminderListener() = default;
virtual void on_reminder(const Reminder& reminder) = 0;
};
// The only listener: sends the reminder through the MailSender, then adds
// 1 to context->sent. The count is a side effect hidden inside a listener,
// so run's return value depends on every earlier run that shared the
// same context.
class MailListener final : public ReminderListener {
public:
MailListener(MailSender& sender, std::shared_ptr<ReminderContext> context);
void on_reminder(const Reminder& reminder) override; // sends, then counts
private:
MailSender* sender_; // borrowed: the sender must outlive this listener
std::shared_ptr<ReminderContext> context_;
};
// Singleton, for an object that one function would replace.
// The constructor is private and copying is deleted, so the only
// ReminderService is the one instance() returns. It lives until the
// program ends, so whatever one caller or test leaves in it (a context,
// a strategy, listener pointers), the next caller finds.
class ReminderService final {
public:
// Returns a reference to the one service, created on the first call.
static ReminderService& instance();
ReminderService(const ReminderService&) = delete;
ReminderService& operator=(const ReminderService&) = delete;
// Must be called before run. Takes a share of the context, and takes
// ownership of the strategy (std::unique_ptr, moved in).
void configure(std::shared_ptr<ReminderContext> context,
std::unique_ptr<SelectionStrategy> strategy);
// Stores the listener's address. Nothing stops the same listener being
// added twice, and nothing removes it when the listener is destroyed.
void subscribe(ReminderListener& listener); // keeps a pointer; never forgets it
// Throws std::logic_error unless configure has run since the last reset.
// Returns the running total in the shared context, not this run's count.
int run(const std::vector<Loan>& loans); // returns context->sent
void reset(); // for tests: forget everything
private:
ReminderService() = default; // private: only instance() can create one
std::shared_ptr<ReminderContext> context_;
std::unique_ptr<SelectionStrategy> strategy_;
// Raw pointers to listeners the service does not own. Each one dangles
// as soon as its listener is destroyed, unless reset() runs first.
std::vector<ReminderListener*> listeners_;
};

run asks the strategy for the loans, builds each reminder with a builder from the factory, and tells every listener. The one listener sends the mail and adds one to the shared count:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.cpp
// Sends a reminder for every loan the strategy selects, by way of every
// subscribed listener. Each step goes through a pattern, and the real
// work (pick the loans due tomorrow, make the text, send it, count it)
// is spread over four classes and a shared context.
int ReminderService::run(const std::vector<Loan>& loans) {
// A singleton can be used before it is set up, so run has to check at
// run time what a constructor parameter would have guaranteed.
if (!context_ || !strategy_) {
throw std::logic_error{"ReminderService::run before configure"};
}
// select returns a new vector of the chosen loans. The range-for keeps
// that temporary vector alive until the loop ends.
for (const Loan& loan : strategy_->select(loans)) {
// A fresh heap-allocated builder for each reminder, from the factory.
const auto builder = ReminderFactory::create_builder();
// Each setter returns the builder itself, so the calls chain.
const Reminder reminder = builder->to(loan.member_email).title(loan.title).due(loan.due).build();
// Calls every stored pointer. If a listener was subscribed twice it
// is called twice; if it has been destroyed, this call is
// undefined behaviour.
for (ReminderListener* listener : listeners_) {
listener->on_reminder(reminder);
}
}
// Not "how many this run sent": the listener has been adding to this
// shared total on every run since the context was created.
return context_->sent;
}

main must create the context, the listener, and the strategy, give the same context to the listener, the strategy, and the service, configure the singleton, subscribe the listener, and then clean up:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Six objects or calls to set up, and a clean-up at the end, all for one
// job. The context starts with today's date and sent = 0, and is shared:
// main, the listener, the strategy, and the service each end up holding
// a copy of the pointer.
auto context = std::make_shared<before::ReminderContext>(before::ReminderContext{today});
PrintingSender printer{std::cout}; // prints each reminder to the console
before::MailListener listener{printer, context};
// `auto&` binds a reference to the one service; `auto` alone would try
// to copy it, and copying is deleted.
auto& service = before::ReminderService::instance();
service.configure(context, std::make_unique<before::DueTomorrow>(context));
service.subscribe(listener); // the service now holds &listener
const int sent_before = service.run(loans);
std::cout << "before: sent " << sent_before << '\n';
service.reset(); // the service keeps &listener, a local; forget it before it dies
How this code works: What one call to run does

Follow service.run(loans) from main, with today set to 18 November and three loans: Dune and Ulysses due on the 19th, Emma on the 20th.

  1. run checks it was configured. configure gave it the context and a DueTomorrow; without them it throws std::logic_error.
  2. The strategy picks the loans. DueTomorrow::select reads context_->today, the shared date, adds one day, and returns copies of the loans due then: Dune and Ulysses.
  3. For each picked loan, a factory makes a builder. ReminderFactory::create_builder allocates a ReminderBuilder, and the chained calls fill it in and build the Reminder. The builder is destroyed at the end of each loop step.
  4. Every subscribed listener is told. The one MailListener calls printer.send, which prints the line, and then does ++context_->sent.
  5. run returns context_->sent, which is now 2.
  6. main calls reset(). The service still holds &listener, the address of a local variable in main, and the service itself lives until after main returns. reset drops that pointer, and the context and strategy with it.

Steps 2, 4, and 5 are where the trouble is. The date the strategy uses and the count run returns are not inputs or results of run: they live in an object that four holders share and that any of them can change. And step 6 is a rule every caller has to remember, because the service keeps a pointer it does not own.

It works. It prints the two reminders due on 19 November and “before: sent 2”. The trouble is everything else it does.

The pattern-heavy version: eight new types, plus the MailSender interface, and one context shared by four owners
Text description of the diagram

A class diagram of the pattern-heavy version. ReminderService is a singleton. It owns one SelectionStrategy, whose only implementation is DueTomorrow, and keeps raw pointers to ReminderListener objects, whose only implementation is MailListener. It uses ReminderFactory, which creates a ReminderBuilder. ReminderContext, with the fields today and sent, is shared by ReminderService, DueTomorrow, and MailListener (and by main, not shown). MailListener changes sent and uses the MailSender interface to send mail. MailSender is the only type here that the requirements need.

Diagram source (Mermaid)
classDiagram
class ReminderService {
  <<singleton>>
  -context_ shared_ptr
  -strategy_ unique_ptr
  -listeners_ vector~ReminderListener*~
  +instance()$ ReminderService&
  +configure(context, strategy)
  +subscribe(listener)
  +run(loans) int
  +reset()
}
class SelectionStrategy {
  <<interface>>
  +select(loans) vector~Loan~*
}
class DueTomorrow {
  -context_ shared_ptr
}
class ReminderListener {
  <<interface>>
  +on_reminder(reminder)*
}
class MailListener {
  -sender_ MailSender*
  -context_ shared_ptr
}
class ReminderFactory {
  +create_builder()$ unique_ptr~ReminderBuilder~
}
class ReminderBuilder {
  +to(email)
  +title(title)
  +due(date)
  +build() Reminder
}
class ReminderContext {
  +today Date
  +sent int
}
class MailSender {
  <<interface>>
  +send(reminder)*
}
SelectionStrategy <|.. DueTomorrow
ReminderListener <|.. MailListener
ReminderService *-- SelectionStrategy : owns one
ReminderService o-- ReminderListener : raw pointers
ReminderService ..> ReminderFactory : uses
ReminderFactory ..> ReminderBuilder : creates
ReminderService o-- ReminderContext : shares
DueTomorrow o-- ReminderContext : shares
MailListener o-- ReminderContext : shares, changes sent
MailListener --> MailSender : sender_ (not owned)

Two kinds of state cause most of the damage here:

  • Shared mutable state: the ReminderContext is held by main, the strategy, the listener, and the service, and any of them can change it. The listener does, on every reminder.
  • Global state: the service is a singleton, so it outlives every test and every caller, and whatever one of them leaves in it, the next one finds.

The three tests below pass. Each one pins down behaviour that the requirements did not ask for.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_reminders.cpp
// LLD_TEST(name) defines one test, and LLD_CHECK_EQ(actual, expected)
// records a failure, printing both values, unless actual == expected.
// They come from the site's small test header, lld_test.hpp. `loans` and
// `today` (18 November 2026) are shared by every test in this file: Dune
// and Ulysses are due on the 19th, Emma on the 20th.
// These three tests pass. Each one pins down behaviour of the
// pattern-heavy version that nobody asked for.
// Start-up code that runs twice (a reload, a second test) subscribes twice.
LLD_TEST(before_a_second_subscribe_sends_every_reminder_twice) {
auto& service = before::ReminderService::instance();
service.reset(); // the singleton outlives every test, so each must clear it first
RecordingSender sender;
auto context = std::make_shared<before::ReminderContext>(before::ReminderContext{today});
before::MailListener listener{sender, context};
service.configure(context, std::make_unique<before::DueTomorrow>(context));
service.subscribe(listener);
service.subscribe(listener); // accepted: the same pointer is stored twice
service.run(loans);
LLD_CHECK_EQ(sender.sent.size(), std::size_t{4}); // two reminders, each sent twice
service.reset(); // and clear it after, or the next test calls a destroyed listener
}
// The count lives in the shared context, so it is never "this run's" count.
LLD_TEST(before_the_count_includes_earlier_runs) {
auto& service = before::ReminderService::instance();
service.reset();
RecordingSender sender;
auto context = std::make_shared<before::ReminderContext>(before::ReminderContext{today});
before::MailListener listener{sender, context};
service.configure(context, std::make_unique<before::DueTomorrow>(context));
service.subscribe(listener);
LLD_CHECK_EQ(service.run(loans), 2);
// The same loans and the same day, yet 4: the 2 from the first run plus
// this run's 2, because the listener keeps adding to context->sent.
LLD_CHECK_EQ(service.run(loans), 4);
service.reset();
}
// Anyone holding the context can change what the strategy selects.
LLD_TEST(before_a_change_elsewhere_changes_the_selection) {
auto context = std::make_shared<before::ReminderContext>(before::ReminderContext{today});
// const, yet its answer changes: it reads the date through the pointer.
const before::DueTomorrow strategy{context};
LLD_CHECK_EQ(strategy.select(loans).size(), std::size_t{2}); // Dune, Ulysses
context->today += days{1}; // say, a report that also holds the context
// Today is now the 19th, so "tomorrow" is the 20th: only Emma.
LLD_CHECK_EQ(strategy.select(loans).size(), std::size_t{1});
}

To know what run returns, it is not enough to read run. The count is context_->sent, which every holder of the context can change, so you must find every holder and know what each did before this call. The second test shows the result: the first run returns 2, the second returns 4, because the count is the total of every run since the context was made. FR-2 asked for this run’s count, and this design cannot give it without the caller remembering the old value and subtracting.

The third test shows the same problem from the other side. Code that holds the context, here a pretend report, moves today forward one day, and the strategy now selects a different set of loans. Nothing called the strategy, and nothing in the strategy changed. A reader looking at DueTomorrow cannot see that it depends on what some other object did to a shared value.

std::shared_ptr is not the problem. It answers “who deletes the context?”, and it answers that correctly. It says nothing about “who may change it?”, and for a shared_ptr<T> to a non-const T the answer is “anyone who has a copy”. Sharing a read-only object, created with std::make_shared<const ReminderContext>(...) so that no non-const handle exists, would be far less risky, but then sent could not be counted in it. That is a clue: the count was never shared data. It is the result of one run.

  • Every test that uses the service must reset it, before and after. Before, because an earlier test may have left a listener or a context in it. After, because the listener is a local variable of the test, and the service still holds a pointer to it when the test returns.
  • reset() exists only for tests. A function whose only purpose is to undo global state between tests is a sign the state should not be global.
  • Start-up mistakes are silent. The first test subscribes the same listener twice, which a reload or a second call to the set-up code could do. The service accepts it, and every member gets each reminder twice.
  • The tests cannot run in parallel, because they all use the one service. FR-3’s “any order” holds only as long as every test resets correctly.

The count is a plain int that every run changes. In a scratch program in which two threads called run on the singleton at the same time, Clang’s ThreadSanitizer reported a data race on ++context_->sent, in MailListener::on_reminder. A data race is undefined behaviour in C++, not only a wrong number.

Making sent a std::atomic<int> would remove the race on the counter but not the mistake: each thread’s count would then include the other thread’s reminders. Both threads would also still call the one subscribed listener and its one sender, which would need to be thread-safe too, and the listeners_ vector would need a lock, in case one thread subscribes while another runs. (ReminderContext would also stop being copyable, because std::atomic is not.) Every fix adds more code to guard state that did not need to be shared.

The service keeps raw pointers to its listeners and lives until the program ends, because it is a function-local static. Every listener is some other code’s object, usually a local variable that is destroyed long before that. Forgetting reset() leaves the service pointing at a destroyed listener. In a scratch program in which a function subscribed a local listener and returned without calling reset(), the next run called the destroyed listener, and AddressSanitizer reported a stack-use-after-return. The Observer page shows how to write subscriptions that cannot dangle, for programs that do need Observer.

Every pattern resolves a particular force: a pressure in the problem, such as “the caller must not name the concrete class” or “listeners come and go while the program runs”. For each pattern in the design, name its force and look for it in the requirements.

Pattern or abstraction The force it resolves Present here? Replace with
Strategy several interchangeable rules, chosen by the caller or while the program runs no: one rule, and no second one is asked for the if inside one function
Builder many optional parts, with rules about how they combine, checked before creating no: two required strings, no rules a struct, created with {email, text}
Factory the caller must not name the concrete type no: one type, which every caller may name nothing (the builder goes too)
Observer a subject that must not depend on its listeners (often because they come and go, or live in another layer) no: one listener, known when the program is written a direct call to sender.send
Singleton a type that truly cannot have a second instance no: tests want their own, and a second branch might want one a function that main calls
Shared context (not a named pattern) data that many objects read today: read-only; sent: the result of one run, not shared a parameter, and a return value
MailSender a boundary with a system outside the program; tests need a fake yes: C-1 and FR-3 keep it

The question is not “could this pattern apply?”. Almost any pattern could. The question is “which force in these requirements does it resolve?” When there is no answer, the pattern is speculative generality, and it costs reading, testing, and change effort every day for a problem that is not present.

Two functions. The first decides which reminders to send; the second sends them:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

reminders.hpp
// The reminders to send today: one for each loan due tomorrow.
// A pure function: it reads only its arguments and changes nothing, so the
// same loans and date always give the same reminders. `today` is a
// parameter, so a test can pass any date.
std::vector<Reminder> reminders_due(const std::vector<Loan>& loans, Date today);
// Sends today's reminders and returns how many were sent.
// Borrows loans and sender for the length of the call and keeps neither.
// The count is a return value, so it is this call's count and nothing
// else's.
int send_reminders(const std::vector<Loan>& loans, Date today, MailSender& sender);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

reminders.cpp
std::vector<Reminder> reminders_due(const std::vector<Loan>& loans, Date today) {
// Date is std::chrono::sys_days, a count of days, so adding one day
// handles month and year ends: 2026-11-30 plus one day is 2026-12-01.
const Date tomorrow = today + std::chrono::days{1};
std::vector<Reminder> reminders;
for (const Loan& loan : loans) {
if (loan.due == tomorrow) {
// The braces build a Reminder from its two fields, in order: the
// address it goes to, and the text.
reminders.push_back({loan.member_email,
"'" + loan.title + "' is due back on " + to_text(loan.due)});
}
}
return reminders;
}
// Decide first, with the pure function, then do the one thing that
// reaches outside the program: send.
int send_reminders(const std::vector<Loan>& loans, Date today, MailSender& sender) {
const std::vector<Reminder> reminders = reminders_due(loans, today);
for (const Reminder& reminder : reminders) {
sender.send(reminder);
}
// size() is an unsigned std::size_t; static_cast<int> converts it to
// the int this function returns, on purpose and visibly.
return static_cast<int>(reminders.size());
}
  • reminders_due is a pure function. Its result depends only on its arguments: the same loans and the same date always give the same reminders. All of FR-1’s rule is here, and its tests need no fake and no set-up.
  • send_reminders is the only code that reaches outside, and it does so through MailSender, which it is given. Nothing is global.
  • The count is a return value, so it is always this run’s count (FR-2). Two calls, or two threads with their own senders, cannot mix their counts.
  • Today’s date is a parameter. A test, or a “what would tomorrow send?” preview, passes any date it likes, without changing an object that something else reads.

class Loan

a struct: plain data

Data members

  • std::string member_email;
  • std::string title;
  • Date due; std::chrono::sys_days

class Reminder

a struct: plain data

Data members

  • std::string to;
  • std::string text;

interface (abstract class) MailSender

Member functions

  • virtual void send(const Reminder& reminder) = 0;

class PrintingSender final

stands in for the real mail system in this example

Member functions

  • explicit PrintingSender(std::ostream& out);

class RecordingSender final

a fake for tests

Data members

  • std::vector<Reminder> sent; public, so tests can read it

namespace global

not a real namespace: free functions at file scope

Functions

  • std::vector<Reminder> reminders_due(const std::vector<Loan>& loans, Date today); pure
  • int send_reminders(const std::vector<Loan>& loans, Date today, MailSender& sender); returns this run's count
The simplified version: plain data, two functions, and one interface at the boundary

The outline leaves out to_text(Date), which formats a date as 2026-11-19, the defaulted operator== on Reminder that the tests use, and the send overrides of the two senders.

Before, main, a singleton, and two other objects share one changing context; after, main calls one function, which uses the one interface that is needed
Text description of the diagram

Two parts, before and after. A dashed arrow means “uses”, and a solid arrow means “creates”. The arrow from Before to After shows the simplification. Before: main configures ReminderService::instance(), one global object, and subscribes a listener to it. The service uses DueTomorrow to select loans, uses ReminderFactory, which creates a ReminderBuilder, and calls MailListener, which uses MailSender. The strategy reads today from ReminderContext, the listener adds to its sent count, and the service returns that count. main created the context and still holds it, so main, the service, the strategy, and the listener share one changing context. After: main calls send_reminders with the loans, today’s date, and a sender. send_reminders calls the pure function reminders_due and uses MailSender to send each reminder. Nothing is shared or global.

Diagram source (Mermaid)
flowchart TB
subgraph Before
  BM["main"] -.->|"configure, subscribe"| BS["ReminderService::instance()<br/>one global object"]
  BS -.->|"select"| BT["DueTomorrow"]
  BS -.->|"create_builder"| BF["ReminderFactory"]
  BF -->|"creates"| BB["ReminderBuilder"]
  BS -.->|"on_reminder"| BL["MailListener"]
  BL -.->|"send"| BX["MailSender"]
  BT -.->|"reads today"| BC["ReminderContext<br/>shared and changed"]
  BL -.->|"adds to sent"| BC
  BS -.->|"returns sent"| BC
  BM -.->|"creates, holds"| BC
end
subgraph After
  AM["main"] -.->|"send_reminders(loans, today, sender)"| AF["send_reminders"]
  AF -.->|"reminders_due(loans, today)"| AR["reminders_due<br/>pure"]
  AF -.->|"send"| AX["MailSender"]
end
Before --> After

MailSender stays, and it is worth saying exactly why:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

loans.hpp
// The mail service is outside the program, so it stays behind an
// interface: the real one sends mail, and tests use a fake.
// One pure virtual function: each kind of sender supplies its own send.
// The code that sends reminders takes a MailSender& and never knows
// whether it is talking to the real service or to a test's fake.
class MailSender {
public:
// Virtual, so a sender deleted through a MailSender pointer is
// destroyed correctly.
virtual ~MailSender() = default;
virtual void send(const Reminder& reminder) = 0;
protected:
// Protected: a derived class can be built and copied, but code cannot
// assign one MailSender& to another, which would copy only the base
// part (slicing).
MailSender() = default;
MailSender(const MailSender&) = default;
MailSender& operator=(const MailSender&) = default;
};
  • There is a real boundary. The mail system is outside the program (C-1). Code on the other side can fail, be slow, or send email that cannot be taken back.
  • There are two implementations today, not one “for later”: the real one, and the fake that tests use to check what was sent (FR-3). In this example, PrintingSender stands in for the real one and prints each reminder.
  • It is small. One function, which the rest of the program calls in one place. Its protected copy operations stop one MailSender& from being assigned to another, which would copy only the base part, while derived classes can still be copied.

The simplification did not remove every abstraction. It removed the ones with no force behind them, and kept the one that has two.

Counted on the example’s files, leaving out blank lines and lines that hold only a comment (the files carry long explanatory comments, which would swamp the comparison):

Version Files Lines New types
pattern-heavy before.hpp, before.cpp 141 8, for five patterns and the context
simplified reminders.hpp, reminders.cpp 26 0 (two functions)

Both versions use the same Loan, Reminder, and MailSender, from loans.hpp, which is not counted. The line count matters less than what a reader must hold in their head: the simplified functions keep no state of their own between calls.

  • After: send_reminders borrows loans and sender for the length of the call and keeps nothing. The reminders are returned by value. No object outlives the call, so nothing can dangle, and there is no clean-up to forget.
  • Before: the context has four owners and lives until the last one lets go. The service is a function-local static, destroyed after main returns. It keeps raw pointers to listeners that it does not own and that are destroyed long before it is, so every caller must remember reset().

Shorter lifetimes are easier to reason about. An object that exists only during one call cannot be changed by anything outside that call.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// The same job, simplified: one object to make, one call, and nothing
// to clean up. The date and the sender are plain arguments.
PrintingSender sender{std::cout};
const int sent = send_reminders(loans, today, sender);
std::cout << "after: sent " << sent << '\n';
Expected output
to ana@example.com: 'Dune' is due back on 2026-11-19
to sam@example.com: 'Ulysses' is due back on 2026-11-19
before: sent 2
to ana@example.com: 'Dune' is due back on 2026-11-19
to sam@example.com: 'Ulysses' is due back on 2026-11-19
after: sent 2

Read the output against the requirements:

  • Both versions send the same two reminders, for the two loans due on 19 November, naming the book and the date (FR-1). Emma, due on the 20th, gets no reminder.
  • Both report 2 for this first run (FR-2). Only the simplified version would still report 2 on a second run; the second before-test shows the pattern-heavy version reporting 4.

The tests of the simplified version need no reset, share nothing, and can run in any order (FR-3):

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_reminders.cpp
// The simplified version's tests: no reset, no shared object, no set-up
// beyond the data. LLD_CHECK(condition) records a failure if the condition
// is false; it is used for the vector comparison, which LLD_CHECK_EQ
// could not print. LLD_TEST and LLD_CHECK_EQ are as above.
// The rule alone, with no sender at all, for three different days.
LLD_TEST(reminders_are_for_loans_due_tomorrow_only) {
const std::vector<Reminder> reminders = reminders_due(loans, today);
const std::vector<Reminder> expected{
{"ana@example.com", "'Dune' is due back on 2026-11-19"},
{"sam@example.com", "'Ulysses' is due back on 2026-11-19"},
};
LLD_CHECK(reminders == expected);
LLD_CHECK(reminders_due(loans, today - days{1}).empty()); // nothing due on the 18th
// From the 19th, tomorrow is the 20th.
LLD_CHECK_EQ(reminders_due(loans, today + days{1}).size(), std::size_t{1}); // Emma
}
// Two calls each return 2, this call's count, while the one fake sender
// records all 4 reminders it was given.
LLD_TEST(each_send_counts_only_its_own_reminders) {
RecordingSender sender;
LLD_CHECK_EQ(send_reminders(loans, today, sender), 2);
LLD_CHECK_EQ(send_reminders(loans, today, sender), 2);
LLD_CHECK_EQ(sender.sent.size(), std::size_t{4});
}
// "Tomorrow" from 30 November must be 1 December, not 31 November.
// year{2026} / December / 1 is std::chrono's way of writing a date.
LLD_TEST(reminders_cross_a_month_end) {
const Date last_day = year{2026} / November / 30;
const std::vector<Loan> december{{"ana@example.com", "Dune", year{2026} / December / 1}};
const std::vector<Reminder> reminders = reminders_due(december, last_day);
LLD_CHECK_EQ(reminders.size(), std::size_t{1});
LLD_CHECK_EQ(reminders.front().text, std::string{"'Dune' is due back on 2026-12-01"});
}
  • reminders_are_for_loans_due_tomorrow_only tests the rule with no fake at all, for three different dates.
  • each_send_counts_only_its_own_reminders checks FR-2 directly: two runs each return 2, and the fake received 4.
  • reminders_cross_a_month_end checks that “tomorrow” from 30 November is 1 December, which std::chrono date arithmetic handles.

The example does not send real email, retry a failed send, or remember which reminders were already sent if the program is run twice in one day. Each of those would be a new requirement, and each would be added to send_reminders or to a real MailSender, not to a pattern chosen in advance.

A removed pattern is not banned. It comes back when its force arrives, and adding it then is a small change, because the simple code is small.

  • “Also remind members three days before.” reminders_due takes the number of days, or is called twice. No pattern.
  • “Some branches send text messages instead of email, set in each branch’s settings.” Another sender implementation, a text-message sender, chosen in main from the settings. The member’s contact details and the interface’s name (ReminderSender, say) change too; the rule and send_reminders do not.
  • “Each branch chooses its own rule: due tomorrow, due in three days, or overdue.” Now there are several rules, chosen while the program runs. That is the force behind Strategy, and a rule parameter (an interface, a std::function, or an enum with a switch if the set is fixed) earns its place.
  • “A statistics page and an audit log, added as plugins, must react to each reminder sent.” Now listeners come and go, and the sender must not know them. That is the force behind Observer, written there with subscriptions that cannot dangle.
  • “The reminders run on a background thread while a web page shows the count.” The simplified version returns the count to whoever called it, which hands it to the page. Handing a value from one thread to another still needs synchronisation, such as std::async and a std::future, but that is one hand-off, not a counter shared by every object. (A count that updates live during a run would be a new requirement.)

Adding a pattern before its second case exists is sometimes right:

  • A published interface that other teams or customers implement, where changing it later would break their code.
  • A plugin boundary, where the implementations are not written by you and cannot be listed in main.
  • A requirement with a date, such as a second payment provider that is already scheduled, as opposed to “we might need it some day”.
  • A framework that requires it, such as a test framework or GUI library whose extension point is an interface.

The cost of unnecessary abstraction discusses the same judgement for interfaces and factories in general.

  • Class names that are pattern names (...Strategy, ...Factory, ...Builder, ...Listener) with one implementation and no test fake.
  • A pattern for each noun or verb in the requirements, chosen before any code was written.
  • A context, manager, or service object passed to, or reached by, most of the program, and changed by several parts of it.
  • A reset(), clear_for_testing(), or set-up order that every test must follow.
  • More pattern participants than requirements.
  • A change to the behaviour (here, “count this run only”) that is hard because of the structure, not because of the behaviour.

None of these proves a mistake. Each is a reason to ask the Step 1 question.

The cost of unnecessary abstraction lists the general steps for removing an abstraction. For a pattern-heavy design, an order that keeps each step small is:

  1. Pin the behaviour first with tests that record what the old code does, using a fake at the real boundary (here, RecordingSender).
  2. Remove the singleton. Make the object an ordinary one, created in main and passed in, as on the Singleton page. This alone removes reset() and lets tests run independently.
  3. Split the shared context. Data that is only read becomes a parameter; results become return values. When the context is empty, delete it.
  4. Inline single-implementation patterns: the one strategy becomes its if, the one listener becomes a direct call.
  5. Replace a builder without rules by creating the struct directly, and delete the factory that made the builder.
  6. Keep the abstractions at real boundaries, and check each one still has its two implementations.

Run the tests after each step. In this example, the simplified version was written next to the pattern-heavy one, and main runs both on the same loans, so the output above shows that they send the same reminders.

  • Removing the one abstraction that earns its place. Calling the mail library directly from send_reminders would make it shorter, and would make every test send real email (or fail without a network).
  • Replacing a singleton with a global variable or a static member. The same hidden dependency, under another name.
  • Making the counter atomic and calling the problem solved. The counter race goes; the count that mixes runs, and the shared listener and sender, stay.
  • Treating std::shared_ptr as a fix for shared state. It manages lifetime. It does not control who changes the object.
  • Going too far. Simple does not mean one long function. The simplified version still separates the rule (a pure function) from the sending (behind an interface), because they change for different reasons and are tested in different ways.
  • Judging a design by how many patterns it has. A design with five patterns can be right, if each one resolves a force that is present. The count of patterns says nothing; the forces say everything.
  • Free functions are normal C++. A class with one static function and no data, such as ReminderFactory, is usually a free function in disguise.
  • Aggregates replace simple builders. A struct with public members is created with braces. C++20 designated initializers name the fields: Reminder{.to = email, .text = text}.
  • std::shared_ptr<const T> shares an object without letting those holders change it. To make it truly read-only, create it with std::make_shared<const T>(...), so that no non-const handle exists. If a design needs shared_ptr<T> to a mutable object, ask who changes it and whether the others need to see the change.
  • Return results; do not accumulate them in shared objects. A return value belongs to one call, so it cannot be mixed with another call’s result.
  • A raw pointer member to an object owned elsewhere needs a stated rule about which outlives which. When the set of objects is fixed at start-up, owning them (a std::vector<std::unique_ptr<T>> passed to the constructor) removes the rule entirely, as the exercise answer shows.

Exercise: Simplify an alert system, and justify each choice

A server room has a temperature sensor. When a reading is above a limit, the program alerts every channel configured for that room: email, a pager, or both, read from a settings file at start-up. Tests must check alerts without sending email or paging anyone. The current design:

// An interface for "should this reading raise an alert?". It has one
// implementation, below.
class AlertRule { // Strategy
public:
virtual ~AlertRule() = default;
virtual bool should_alert(double celsius) const = 0;
};
// True when a reading is above the limit given to the constructor.
class AboveLimit final : public AlertRule { // the only rule
public:
explicit AboveLimit(double limit) : limit_{limit} {}
bool should_alert(double celsius) const override { return celsius > limit_; }
private:
double limit_;
};
// Somewhere an alert can go: email or a pager.
class AlertChannel { // Observer
public:
virtual ~AlertChannel() = default;
virtual void alert(const std::string& message) = 0;
};
// EmailChannel and PagerChannel implement AlertChannel.
// The one manager, reached through instance(). It owns the rule but only
// borrows the channels: add_channel stores a raw pointer, which dangles
// if that channel is destroyed first.
class AlertManager final { // Singleton
public:
static AlertManager& instance();
void set_rule(std::unique_ptr<AlertRule> rule);
void add_channel(AlertChannel& channel); // keeps a pointer
void on_reading(double celsius); // alerts each channel if the rule says so
private:
AlertManager() = default;
std::unique_ptr<AlertRule> rule_;
std::vector<AlertChannel*> channels_;
};
  1. For each of the three patterns, name the force it would resolve and say whether this program has it.
  2. Write the simplified class, and say who owns what.
  3. Name one requirement change that would bring the rule interface back.
Show the explained answer

1.

  • Singleton (AlertManager): no force. Nothing stops a program from having two alert managers, and tests want one each. A second server room would want a second one too. Create it in main.
  • Strategy (AlertRule): no force. There is one rule, and its only data is a number. A double member does the same job.
  • Observer (add_channel): no force. The channels are fixed at start-up, and nothing subscribes later, so the subject does not need to be independent of listeners that come and go.
  • But the AlertChannel interface stays, as an interface at a boundary rather than as an Observer. There are two real implementations, chosen while the program runs from the settings file, both talk to systems outside the program, and tests need a fake. A list of channels is justified too, because “both” is a valid setting. Since the list is fixed at start-up, the raw pointers can become owned objects.

2.

// The interface stays: two real channels and a test fake implement it.
class AlertChannel {
public:
virtual ~AlertChannel() = default;
virtual void alert(const std::string& message) = 0;
protected:
// Derived classes can be built and copied; code cannot assign one
// AlertChannel& to another and copy only the base part.
AlertChannel() = default;
AlertChannel(const AlertChannel&) = default;
AlertChannel& operator=(const AlertChannel&) = default;
};
// Owns its channels and holds the limit as a plain number. Created in
// main (or in a test) and passed to whoever needs it: no global.
class Alerter final {
public:
// The vector of unique_ptrs is taken by value and moved into channels_,
// so the Alerter becomes the only owner of every channel. A null
// channel is refused with std::invalid_argument, so on_reading never
// has to check.
Alerter(double limit_celsius, std::vector<std::unique_ptr<AlertChannel>> channels)
: limit_celsius_{limit_celsius}, channels_{std::move(channels)} {
for (const auto& channel : channels_) {
if (!channel) {
throw std::invalid_argument{"an alert channel must not be null"};
}
}
}
// At or below the limit: nothing to do. Above it: one message, sent to
// every channel in the order they were given.
void on_reading(double celsius) {
if (celsius <= limit_celsius_) {
return;
}
const std::string message = "temperature " + std::to_string(celsius) + " is above the limit";
for (const auto& channel : channels_) {
channel->alert(message);
}
}
private:
double limit_celsius_;
std::vector<std::unique_ptr<AlertChannel>> channels_;
};

main reads the settings, creates the channels the room needs, and moves them into the Alerter, which owns them for as long as it exists. Nothing can point at a destroyed channel, and a channel cannot be added twice by a second call to set-up code, because there is no add_channel. A test creates an Alerter with a fake channel that records each message into a std::vector<std::string> the test owns; the vector is declared before the Alerter, so it outlives it. (This answer, with such a fake, was compiled and run with GCC and Clang.)

3. For example: “some rooms alert on a fast rise, more than 2 °C in five minutes, instead of a fixed limit, chosen per room in the settings”. Now there are several rules, chosen while the program runs, and one of them keeps state between readings, so the rule’s signature also gains a time for each reading. A rule interface, or a std::variant of rule types if the set is fixed, earns its place.

  • Singleton is the most common source of global state in a pattern-heavy design. See Singleton.
  • Strategy and Observer are often added for one implementation or one listener. See Strategy and Observer for the forces that justify them.
  • Builder is often added for a struct with no rules. See Builder for when its checks earn its place.
  • Dependency injection is how the simplified version gets its sender. See dependency injection.
  • A pattern earns its place by resolving a force that is present in the requirements. A pattern chosen because a word matches its name usually resolves nothing.
  • Shared mutable state makes results depend on who else changed an object; global state makes every test and every thread share it. The costs are in reasoning, testing, concurrency, and lifetime.
  • std::shared_ptr manages lifetime, not change. A result belongs in a return value, not in a shared counter.
  • Simplify by asking, for each pattern, which force it resolves; keep the abstractions at real boundaries, such as MailSender.
  • A removed pattern comes back when its force arrives, and the simple code makes adding it easy.