Skip to content

Dependency direction and dependency injection

Difficulty: Intermediate

Key concepts

  • dependency direction
  • dependency injection
  • constructor injection
  • composition root
  • test double
  • fake clock
  • What dependency direction means, and why the code that holds the rules should not depend on the code that talks to hardware, files, or the clock.
  • What dependency injection is: passing a class the objects it works with, instead of letting it create or find them.
  • How to choose between injecting by reference (not owned) and by std::unique_ptr (owned), and how to stop a reference from dangling.
  • What a composition root is, and why C++ programs rarely need a DI framework.
  • How to test time-based rules with a fake clock, without waiting.

A bedside alarm clock runs a small C++ program. The requirements:

  1. FR-1 Ring at the wake time (for example 07:00), Monday to Friday. Never at the weekend.
  2. FR-2 Snooze silences it for 9 minutes, then it rings again. At most 3 snoozes; after that, snooze does nothing and it keeps ringing.
  3. FR-3 Stop silences it until the next day.
  4. NFR-1 The rules must be checked by automatic tests on a build machine, which has no speaker and cannot wait until 07:00 on a Monday.
  5. NFR-2 The next model adds a vibration pad. The alarm rules should not change for that.
Idea Question it answers In one sentence
Dependency direction Which code should know about which? Details (hardware, clock, files) should depend on the rules, through interfaces the rules define; not the other way round.
Dependency injection Where does a class get its collaborators? It is given them, usually in its constructor, by the code that creates it.

The two work together. The first decides which interfaces exist and where they live; the second decides how a real or fake implementation reaches the class at run time. The first idea is often called the dependency inversion principle, the “D” in SOLID; the SOLID part of this section returns to it.

Before designing, write down everything the alarm rules need from outside themselves, and ask of each one: is it policy (a rule the product owner decides) or detail (how the device happens to do it)?

Dependency Policy or detail? Changes when… Can a test control it?
“ring at 07:00 on weekdays” policy the product owner changes the rules yes, it is our code
“snooze 9 minutes, 3 times” policy the product owner changes the rules yes, it is our code
the current time detail never in the code; but it moves by itself no, not if read from the system
the speaker driver detail the hardware changes (vibration pad) no, not on a build machine

The two “no” rows are the problem. The rules are the part that matters most, and the part tests most need to check, yet they are welded to two details a test cannot control.

Bad, good, great: where do the time and the bell come from?

Section titled “Bad, good, great: where do the time and the bell come from?”
Before, the alarm rules depend on the system clock and the buzzer; after, the devices and the fakes depend on the alarm rules' interfaces
Text description of the diagram

Two parts, before and after. Before: AlarmClock, which holds the rules, has a dashed arrow labelled “calls” to std::chrono::system_clock, and a solid arrow labelled “owns 1” to Buzzer, the speaker driver. After: the alarm clock header contains AlarmClock and the two interfaces Clock and Bell. The devices header (SystemClock and TerminalBell) and the fakes header (FakeClock and RecordingBell) each have a thick arrow labelled “implements” to the alarm clock header. Only the devices header has a dashed arrow to std::chrono::system_clock. The main function, the composition root, has dashed “uses” arrows to the devices and to the alarm clock header, and a dashed arrow labelled “uses in the simulation” to the fakes. The tests have dashed “uses” arrows to the fakes and to the alarm clock header. No arrow leaves the alarm clock header. A flow arrow from the Before group to the After group shows the refactoring.

Diagram source (Mermaid)
flowchart TB
subgraph Before
  BA["AlarmClock<br/>rules"] -.->|calls| BSC["std::chrono::system_clock"]
  BA -->|owns 1| BZ["Buzzer<br/>speaker driver"]
end
subgraph After
  AR["alarm_clock.hpp<br/>AlarmClock, Clock, Bell"]
  DV["devices.hpp<br/>SystemClock, TerminalBell"] ==>|implements| AR
  FK["fakes.hpp<br/>FakeClock, RecordingBell"] ==>|implements| AR
  DV -.->|calls| ASC["std::chrono::system_clock"]
  MN["main()<br/>composition root"] -.->|uses| DV
  MN -.->|uses| AR
  MN -.->|uses in the simulation| FK
  TS["tests"] -.->|uses| FK
  TS -.->|uses| AR
end
Before --> After

Look at where the arrows point after the change. Every arrow that touches the alarm rules points at them; none leaves alarm_clock.hpp, except to the standard library. The rules are the most stable part (they change only when the product owner asks) and the most valuable part (they are what the tests check), so everything else depends on them. That is what “point dependencies toward stable policy” means.

(The example’s main is a simulation, so it uses the fake clock to make its output repeatable; a real device’s main would create a SystemClock instead, as the comment in the wiring snippet says. SystemClock is compiled in the example but not run or tested, because its answer changes every second.)

interface (abstract class) Clock

what the rules need: the current time

Member functions

  • virtual ~Clock() = default;
  • virtual std::chrono::sys_seconds now() const = 0;

interface (abstract class) Bell

what the rules need: a way to wake someone

Member functions

  • virtual ~Bell() = default;
  • virtual void ring() = 0;
  • virtual void silence() = 0;

class AlarmClock

the rules: when to ring, snooze, stop

Data members

  • const Clock& clock_; not owned; shared with the rest of the program
  • std::unique_ptr<Bell> bell_; owned; never null
  • std::chrono::minutes wake_at_;
  • std::optional<std::chrono::sys_days> rang_on_;
  • std::optional<std::chrono::sys_seconds> snoozed_until_;
  • int snoozes_ = 0;
  • bool ringing_ = false;

Member functions

  • AlarmClock(const Clock& clock, std::unique_ptr<Bell> bell, std::chrono::minutes wake_at);
  • AlarmClock(const Clock&& clock, ...) = delete; no temporary clocks
  • void tick();
  • bool snooze();
  • void stop();
  • bool ringing() const;

class SystemClock

final; the real time

Member functions

  • std::chrono::sys_seconds now() const override;

class TerminalBell

final; stands in for the speaker

Data members

  • std::ostream& out_; not owned

Member functions

  • void ring() override;
  • void silence() override;

class FakeClock

final; test double, moves only when told

Data members

  • std::chrono::sys_seconds now_;

Member functions

  • std::chrono::sys_seconds now() const override;
  • void advance(std::chrono::seconds by);

class RecordingBell

final; test double, writes to a caller-owned log

Data members

  • std::vector<std::string>& log_; not owned

Member functions

  • void ring() override;
  • void silence() override;
After: AlarmClock holds the rules and receives a Clock (not owned) and a Bell (owned); real and fake implementations live in other files

The interfaces, in the alarm clock’s own header:

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

alarm_clock.hpp
// The two things the alarm rules need from the outside world, described
// from the alarm clock's point of view. They live with the alarm clock,
// not with the hardware code.
// "Something that can tell the time." An interface: it has no data and no
// code of its own, only a promise that every kind of clock (the real one,
// or a fake one in a test) can answer now().
class Clock {
public:
// virtual destructor: destroying a real clock through a Clock pointer
// or reference runs the real clock's destructor too.
virtual ~Clock() = default;
// `= 0` makes now() pure virtual: Clock itself has no body for it, and
// every concrete clock must write one. sys_seconds is a point in time,
// counted in whole seconds (UTC, as the page's limits section says).
[[nodiscard]] virtual std::chrono::sys_seconds now() const = 0;
protected:
// Protected, not public: only derived classes can use these. That
// stops code outside the family from copying through Clock references
// (`a = b` for two Clock&), which would copy only the Clock part and
// slice off the rest of the real clock. See the idiom reference,
// "Interfaces: virtual, override, and final".
Clock() = default;
Clock(const Clock&) = default;
Clock& operator=(const Clock&) = default;
};
// "Something that can make a noise and stop." The real one drives a
// speaker; a test one just writes down what it was asked to do.
class Bell {
public:
virtual ~Bell() = default;
virtual void ring() = 0;
virtual void silence() = 0;
protected:
// The same protection against slicing as Clock.
Bell() = default;
Bell(const Bell&) = default;
Bell& operator=(const Bell&) = default;
};

The alarm clock:

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

alarm_clock.hpp
// Rings once a day at wake_at, Monday to Friday. Snooze silences it for
// 9 minutes, at most 3 times; stop silences it until the next day (and,
// if pressed before the wake time, skips today's alarm).
// It never reads the real time or builds its own bell: both come in
// through the constructor (constructor injection), so a test can hand it
// a fake clock and a bell that records what happened.
class AlarmClock {
public:
// One value each, shared by every AlarmClock (static) and fixed when
// compiling (constexpr). Tests use them too, instead of repeating 9 and 3.
static constexpr std::chrono::minutes snooze_length{9};
static constexpr int max_snoozes = 3;
// Throws std::invalid_argument if bell is null or wake_at is not
// within one day. The clock must outlive this object.
// The clock is borrowed (a reference: main keeps it). The bell is
// handed over: std::unique_ptr<Bell> means "you own this now", so the
// caller passes std::make_unique<...>(...) or std::move(a_pointer).
AlarmClock(const Clock& clock, std::unique_ptr<Bell> bell, std::chrono::minutes wake_at);
// A temporary clock would be destroyed at the end of the statement,
// leaving clock_ dangling, so passing one does not compile.
// How: a temporary (such as SystemClock{}) prefers a `&&` parameter,
// so the compiler picks this overload, and `= delete` makes using it
// an error. A named clock still picks the `const Clock&` one above.
AlarmClock(const Clock&& clock, std::unique_ptr<Bell> bell, std::chrono::minutes wake_at) = delete;
// A moved-from alarm clock would have no bell, so moving is not offered.
// (Copying is not offered either: a unique_ptr member cannot be copied.)
AlarmClock(AlarmClock&&) = delete;
AlarmClock& operator=(AlarmClock&&) = delete;
void tick(); // called often (every second) by the main loop
bool snooze(); // false if not ringing or out of snoozes; then nothing changes
void stop();
[[nodiscard]] bool ringing() const { return ringing_; }
private:
void start_ringing();
const Clock& clock_; // not owned; shared with the rest of the program
std::unique_ptr<Bell> bell_; // owned; never null
std::chrono::minutes wake_at_;
// The date of the last alarm (or of a stop), or empty if neither has
// happened yet. Used to ring at most once a day.
std::optional<std::chrono::sys_days> rang_on_;
// When a snooze ends, or empty when not snoozing.
std::optional<std::chrono::sys_seconds> snoozed_until_;
int snoozes_ = 0; // snoozes used this morning; reset when the alarm first rings
bool ringing_ = false;
};

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

alarm_clock.cpp
// The constructor stores what it was given, then checks it. Throwing here
// means an AlarmClock either exists with a bell and a sensible wake time,
// or does not exist at all; no other function needs to check again.
AlarmClock::AlarmClock(const Clock& clock, std::unique_ptr<Bell> bell, minutes wake_at)
// std::move hands the bell's ownership from the parameter to bell_.
: clock_{clock}, bell_{std::move(bell)}, wake_at_{wake_at} {
if (!bell_) throw std::invalid_argument("alarm clock needs a bell"); // null pointer
// The wake time is a time of day: from 00:00 up to, but not including, 24:00.
if (wake_at < minutes{0} || wake_at >= days{1}) {
throw std::invalid_argument("wake time must be within one day");
}
}
// Called every second. Decides whether to start ringing, from two
// sources: a snooze that has run out, or the daily wake time. The same
// rules as the "before" version, but the time comes from the injected
// clock_, so a test decides what time it is.
void AlarmClock::tick() {
if (ringing_) return; // already ringing: nothing to decide
const sys_seconds now = clock_.now(); // the injected clock: real or fake
// While snoozed, only one question matters: is the snooze over yet?
// `if (snoozed_until_)` is true when the optional holds a time, and
// *snoozed_until_ is that time.
if (snoozed_until_) {
if (now >= *snoozed_until_) {
snoozed_until_.reset(); // empty it: no longer snoozing
start_ringing();
}
return; // either way, the daily check below does not run while snoozed
}
const sys_days today = floor<days>(now); // round down to midnight today
const weekday day{today};
// Already rang (or was stopped) today, or the weekend: stay quiet.
if (rang_on_ == today || day == Saturday || day == Sunday) return;
// now - today is the time since midnight: has the wake time arrived?
if (now - today >= wake_at_) {
rang_on_ = today; // so it does not ring again today
snoozes_ = 0; // a new morning: all 3 snoozes are available again
start_ringing();
}
}
// Silences the bell for snooze_length and returns true, or refuses and
// returns false (changing nothing) if it is not ringing or this morning's
// snoozes are used up. tick() starts it ringing again when the time comes.
bool AlarmClock::snooze() {
if (!ringing_ || snoozes_ == max_snoozes) return false;
++snoozes_;
ringing_ = false;
snoozed_until_ = clock_.now() + snooze_length; // 9 minutes from now
bell_->silence(); // -> calls through the pointer; bell_ is never null
return true;
}
// Ends this morning's alarm, whether it is ringing, snoozed, or not
// started yet. Setting rang_on_ to today makes tick() treat today as
// done, which is also how pressing stop before 7:00 skips today.
void AlarmClock::stop() {
rang_on_ = floor<days>(clock_.now()); // quiet until tomorrow, even if pressed early
snoozed_until_.reset(); // cancel a snooze, so it cannot ring again
if (ringing_) bell_->silence(); // only silence a bell that is ringing
ringing_ = false;
}
void AlarmClock::start_ringing() {
ringing_ = true;
bell_->ring();
}
How this code works: AlarmClock: tick, snooze, and stop

The alarm clock keeps a small amount of state, and the three functions only read and change it:

  • ringing_: is the bell ringing right now?
  • rang_on_: the date the alarm last rang, or was stopped (empty at first).
  • snoozed_until_: when the current snooze ends (empty when not snoozing).
  • snoozes_: how many snoozes have been used this morning.

tick asks its questions in order and leaves at the first one that settles it:

  1. Already ringing? Then there is nothing to decide.
  2. Snoozed? Then the only question is whether the snooze has run out. If it has, the snooze is cleared and the bell rings again. Either way, tick returns here, so the daily check below is skipped while snoozed.
  3. Already rang (or stopped) today, or a Saturday or Sunday? Stay quiet.
  4. Is the time since midnight at least wake_at_? Then record today in rang_on_, give back all three snoozes, and ring.

snooze refuses (returns false and changes nothing) unless the bell is ringing and a snooze is left. Otherwise it counts the snooze, stops ringing, sets snoozed_until_ to now plus 9 minutes, and silences the bell. It does not ring again by itself: a later tick sees that the time has come.

stop writes today’s date into rang_on_, so step 3 of tick keeps it quiet until midnight. That one line also explains why pressing stop at 06:59 skips today’s alarm. It clears any snooze, and only calls silence() if the bell was actually ringing.

A trace of the simulated morning below (wake time 07:00):

Call Fake time What happens ringing_ afterwards Prints
tick Mon 06:59 step 4: 06:59 is before 07:00 false nothing
tick Mon 07:00 step 4: wake time reached, rang_on_ = Monday true bell: RING
snooze Mon 07:00 snoozes_ = 1, snoozed_until_ = 07:09 false bell: quiet
tick Mon 07:09 step 2: 07:09 is not before 07:09, so ring true bell: RING
stop Mon 07:09 rang_on_ = Monday, bell was ringing false bell: quiet
tick Mon 07:39 step 3: already rang today false nothing
tick Sat 07:39 step 3: Saturday false nothing

Every time in that table came from a FakeClock. The alarm clock cannot tell the difference, which is the point of injecting the clock.

The real parts, in a separate file that includes alarm_clock.hpp:

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

devices.hpp
// The real parts. They depend on the interfaces in alarm_clock.hpp;
// the alarm clock does not know they exist.
// The real clock: now() reads std::chrono::system_clock and rounds down to
// a whole second. `final` means no class can derive from it; `override`
// asks the compiler to check that now() really replaces Clock::now().
class SystemClock final : public Clock {
public:
[[nodiscard]] std::chrono::sys_seconds now() const override;
};
// Stands in for the speaker driver: writes to a stream it does not own.
// ring() prints " bell: RING" and silence() prints " bell: quiet".
class TerminalBell final : public Bell {
public:
explicit TerminalBell(std::ostream& out) : out_{out} {}
void ring() override;
void silence() override;
private:
std::ostream& out_; // not owned; must outlive the bell
};

And the place where everything is put together:

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

main.cpp
// The composition root: main creates the parts and decides who owns what.
// 2026y / November / 16 is a date (a Monday) written with chrono's `/`
// syntax; sys_days{...} turns it into midnight of that day, and adding
// 6h + 59min gives 06:59. (2026y, 6h, 59min come from chrono_literals.)
const sys_seconds monday_0659 = sys_days{2026y / November / 16} + 6h + 59min;
// Declared before alarm, so it is destroyed after alarm: the reference
// the alarm clock keeps to it stays valid for the alarm's whole life.
FakeClock clock{monday_0659}; // in the real device: SystemClock clock;
// make_unique creates a TerminalBell (printing to std::cout) and the
// unique_ptr is handed straight to the alarm clock, which then owns
// it. 7h is the wake time, 07:00; it converts to minutes{420}.
AlarmClock alarm{clock, std::make_unique<TerminalBell>(std::cout), 7h};
Object Owned by How the user holds it Why
the clock main (a local variable) AlarmClock: const Clock& One clock serves the whole program (the display, the log, the alarm). Nobody but main should destroy it.
the bell AlarmClock std::unique_ptr<Bell> Only the alarm clock rings it, and it should last exactly as long as the alarm clock. unique_ptr says that in the type.
the alarm clock main (a local variable) by name It lives for the whole program.
the output stream the C++ runtime (std::cout) TerminalBell: std::ostream& The bell writes to a stream it did not create.
the test log the test (a local vector) RecordingBell: std::vector<std::string>& The bell is owned by the alarm clock, so the test keeps the log itself and reads it after any call.

The rule of thumb this table follows:

  • Inject by reference when the collaborator is shared, or owned by someone who lives longer, and it can never be missing.
  • Inject by std::unique_ptr when the class should own the collaborator and be its only user.
  • (Inject by std::shared_ptr only when ownership is genuinely shared and nobody can say who lives longest. That is rare in a design like this.)

A reference member comes with one danger: the object it refers to must outlive the class. In main, clock is declared before alarm, so it is destroyed after it, which is what we need: local variables are destroyed in reverse order of declaration. The deleted const Clock&& constructor catches the most common mistake at compile time:

AlarmClock alarm{SystemClock{}, std::make_unique<TerminalBell>(std::cout), 7h};
// error: use of deleted function; the temporary SystemClock would be
// destroyed at the end of this line, and alarm would refer to nothing.

It cannot catch everything. A clock that is a local variable in a function that returns while the alarm clock lives on (for example, inside a std::unique_ptr<AlarmClock> returned from that function) still dangles, and so does a reference bound to a temporary somewhere else first, such as const Clock& clock = make_clock(); in a scope that ends too soon. The deleted overload catches the easy, common case: a temporary passed straight to the constructor.

Choice Why
Clock and Bell live in alarm_clock.hpp They describe what the rules need, so they belong to the rules. If they lived in devices.hpp, the rules would still depend on the devices file, and the arrow would point the wrong way.
Interfaces are tiny (one or two functions) A fake must implement every function. Small interfaces keep fakes to a few lines, and describe exactly what the rules use, nothing more.
Constructor injection After the constructor finishes, the object is complete: there is no moment when it has no clock. Setters would allow a half-built alarm clock.
The constructor checks for a null bell and a bad wake time A unique_ptr can be null; checking once, at the door, lets every other function assume it is not (the “never null” comment is an invariant, not a hope).
Moves are deleted A moved-from alarm clock would have a null bell, which every function assumes is impossible. (The reference member already prevents assignment, but not move construction.)
Clock and Bell have protected copy operations They stop code from assigning one Clock& to another (a = b), which would copy only the Clock part and slice off the real clock; derived classes can still be copied. The composition page explains the same choice for ShippingRate.
now() returns std::chrono::sys_seconds A type that says “a point in time, to the second” is clearer than an int, and std::chrono does the weekday and time-of-day arithmetic correctly.
main is the composition root One place creates the real objects and connects them. Everywhere else just receives what it needs. Reading main tells you the whole wiring.
No DI container In C++, a constructor call is the injection. A framework that builds objects for you adds a dependency, hides the wiring, and usually needs run-time registration. A dozen lines in main do the same job, and the compiler checks them.
Way Looks like Good for Watch out for
constructor, interface (this page) AlarmClock(const Clock&, std::unique_ptr<Bell>, ...) collaborators used by many member functions; swapping at run time or in tests a virtual call per use (rarely matters); reference lifetimes
function parameter tick(sys_seconds now) one function needs the value; pure functions every caller must supply it
template parameter template <class ClockT> class AlarmClock hot code where a virtual call matters; the choice is fixed when compiling code in headers; each choice is a different type; errors are harder to read
std::function AlarmClock(std::function<sys_seconds()> now, ...) a single operation, often a lambda in tests can be empty; copies the callable it is given (wrap it with std::ref to share one)
setter alarm.set_clock(clock) optional collaborators added late (rare) an object that exists without its parts
global or singleton (avoid) Clock::instance().now() rarely; prefer injection hidden dependency; tests interfere with each other; order of start-up

The program runs the real AlarmClock with a FakeClock, and a TerminalBell that prints:

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

main.cpp
// show(what, clock) prints the fake clock's day and time, then `what`.
// Nothing waits: advance() moves the fake clock, then tick() is called
// by hand, as the main loop of a real device would every second.
show("tick", clock);
alarm.tick(); // 06:59: before the wake time, nothing happens
clock.advance(1min);
show("tick", clock);
alarm.tick(); // 07:00 on a Monday: the bell rings
show("snooze", clock);
alarm.snooze(); // quiet until 07:09 (it returns true; not needed here)
clock.advance(9min);
show("tick", clock);
alarm.tick(); // 07:09: the snooze is over, so it rings again
show("stop", clock);
alarm.stop(); // quiet, and today counts as done
clock.advance(30min);
show("tick (already rang today)", clock);
alarm.tick(); // 07:39 Monday: already rang today, stays quiet
clock.advance(days{5});
show("tick (weekend)", clock);
alarm.tick(); // 07:39 Saturday: a weekend, stays quiet
Expected output
Mon 06:59 tick
Mon 07:00 tick
bell: RING
Mon 07:00 snooze
bell: quiet
Mon 07:09 tick
bell: RING
Mon 07:09 stop
bell: quiet
Mon 07:39 tick (already rang today)
Sat 07:39 tick (weekend)

Five simulated days pass without any waiting. The bell rings at 07:00, not at 06:59; snooze silences it, and it rings again at 07:09; after stop, it stays quiet for the rest of Monday; and on Saturday it does not ring.

The test doubles:

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

fakes.hpp
// Test doubles: a clock that only moves when told to, and a bell that
// writes down what it was asked to do.
// A clock that only moves when told to, so a test can jump straight to
// "Monday 06:59" or "Saturday" without waiting. It starts at `start`,
// and now() returns the same time until advance() is called.
class FakeClock final : public Clock {
public:
explicit FakeClock(std::chrono::sys_seconds start) : now_{start} {}
[[nodiscard]] std::chrono::sys_seconds now() const override { return now_; }
// Moves time forward. std::chrono::seconds accepts 1min, 9min, or
// days{5} as well: chrono converts them to seconds exactly.
void advance(std::chrono::seconds by) { now_ += by; }
private:
std::chrono::sys_seconds now_;
};
// A bell that rings nothing: each call adds a word to a log, so a test
// can check afterwards exactly what the alarm clock asked for and in what
// order, for example Log{"ring", "silence"}.
class RecordingBell final : public Bell {
public:
// The log is owned by the caller, so it can still be read after the
// alarm clock (which owns this bell) has gone.
explicit RecordingBell(std::vector<std::string>& log) : log_{log} {}
// emplace_back adds a new std::string, built from "ring", to the end.
void ring() override { log_.emplace_back("ring"); }
void silence() override { log_.emplace_back("silence"); }
private:
std::vector<std::string>& log_; // not owned
};

A test double is any object that stands in for a real collaborator in a test. FakeClock is a fake: a working, simplified implementation. RecordingBell is sometimes called a spy: it records how it was used, so the test can check afterwards.

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

test_alarm.cpp
// The tests use two fixed start times, defined above this snippet:
// monday_0659 (Monday 16 November 2026, 06:59) and saturday_0659 (Saturday
// 21 November 2026, 06:59). Log is std::vector<std::string>, the list of
// words a RecordingBell writes. Every test builds its own clock, log, and
// alarm clock, wakes at 7h, and then moves the fake clock by hand.
//
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false, and LLD_CHECK_THROWS(expression, type) fails
// unless the expression throws that type of exception. They come from
// the site's small test header, lld_test.hpp.
// A clock passed by name is accepted; a temporary one is refused at compile time.
// static_assert is checked by the compiler, not when the tests run: if the
// condition is false, the file does not compile. is_constructible_v asks
// "could an AlarmClock be built from these argument types?". FakeClock&
// stands for a named clock; plain FakeClock stands for a temporary, which
// picks the deleted `const Clock&&` constructor, so the answer is no.
static_assert(std::is_constructible_v<AlarmClock, FakeClock&, std::unique_ptr<Bell>, minutes>);
static_assert(!std::is_constructible_v<AlarmClock, FakeClock, std::unique_ptr<Bell>, minutes>);
// The basic rule, on both sides of the edge: quiet at 06:59, rings at 07:00.
// `log == Log{"ring"}` compares the whole vector: exactly one entry, "ring".
LLD_TEST(rings_at_the_wake_time_on_a_weekday) {
FakeClock clock{monday_0659};
Log log;
AlarmClock alarm{clock, std::make_unique<RecordingBell>(log), 7h};
alarm.tick();
LLD_CHECK(log.empty()); // 6:59, not yet
clock.advance(1min);
alarm.tick();
LLD_CHECK(log == Log{"ring"});
}
// Saturday 07:59, long after the wake time: no ring.
LLD_TEST(stays_quiet_at_the_weekend) {
FakeClock clock{saturday_0659};
Log log;
AlarmClock alarm{clock, std::make_unique<RecordingBell>(log), 7h};
clock.advance(1h);
alarm.tick();
LLD_CHECK(log.empty());
}
// Starts at 07:00, rings, is stopped; two hours later it is still quiet.
// The next day (Tuesday 09:00) it rings again: "once a day", not "once".
// The extra brackets around Log{...} are needed because the comma inside
// the braces would otherwise split the macro's argument in two.
LLD_TEST(rings_once_a_day) {
FakeClock clock{monday_0659 + 1min};
Log log;
AlarmClock alarm{clock, std::make_unique<RecordingBell>(log), 7h};
alarm.tick();
alarm.stop();
clock.advance(2h);
alarm.tick();
LLD_CHECK(log == (Log{"ring", "silence"}));
clock.advance(days{1}); // Tuesday
alarm.tick();
LLD_CHECK(log.back() == "ring");
}
// Snooze at 07:00. At 07:08:59 it is still quiet; one second later, at
// 07:09:00, it rings. The two checks pin the 9-minute edge exactly.
LLD_TEST(snooze_rings_again_after_nine_minutes) {
FakeClock clock{monday_0659 + 1min};
Log log;
AlarmClock alarm{clock, std::make_unique<RecordingBell>(log), 7h};
alarm.tick();
LLD_CHECK(alarm.snooze());
clock.advance(8min + 59s);
alarm.tick();
LLD_CHECK(!alarm.ringing());
clock.advance(1s);
alarm.tick();
LLD_CHECK(alarm.ringing());
}
// Three rounds of snooze, wait 9 minutes, ring again. Each snooze() is
// accepted. The fourth is refused (false), and the alarm keeps ringing.
LLD_TEST(three_snoozes_at_most) {
FakeClock clock{monday_0659 + 1min};
Log log;
AlarmClock alarm{clock, std::make_unique<RecordingBell>(log), 7h};
alarm.tick();
for (int round = 0; round < AlarmClock::max_snoozes; ++round) {
LLD_CHECK(alarm.snooze());
clock.advance(AlarmClock::snooze_length);
alarm.tick();
}
LLD_CHECK(!alarm.snooze());
LLD_CHECK(alarm.ringing());
}
// Ring, snooze (the bell logs "silence"), then stop while snoozed. When
// the snooze would have ended, nothing rings. The log also proves stop did
// not call silence() a second time: the bell was not ringing.
LLD_TEST(stop_while_snoozed_ends_the_morning) {
FakeClock clock{monday_0659 + 1min};
Log log;
AlarmClock alarm{clock, std::make_unique<RecordingBell>(log), 7h};
alarm.tick();
LLD_CHECK(alarm.snooze());
alarm.stop();
clock.advance(AlarmClock::snooze_length);
alarm.tick();
LLD_CHECK(log == (Log{"ring", "silence"})); // no second ring; stop did not silence twice
}
// Stop pressed at 06:59, before the alarm: at 07:00 it stays quiet.
LLD_TEST(stop_before_the_wake_time_skips_today) {
FakeClock clock{monday_0659};
Log log;
AlarmClock alarm{clock, std::make_unique<RecordingBell>(log), 7h};
alarm.stop();
clock.advance(1min);
alarm.tick();
LLD_CHECK(log.empty());
}
// The constructor's two checks: a null bell, and a wake time of 24h (one
// past the last allowed minute, 23:59), each throw std::invalid_argument.
LLD_TEST(refuses_a_missing_bell_or_a_bad_wake_time) {
FakeClock clock{monday_0659};
Log log;
LLD_CHECK_THROWS(AlarmClock(clock, nullptr, 7h), std::invalid_argument);
LLD_CHECK_THROWS(AlarmClock(clock, std::make_unique<RecordingBell>(log), 24h),
std::invalid_argument);
}

(LLD_TEST, LLD_CHECK, and LLD_CHECK_THROWS are this site’s small test macros: a named test, a check that must be true, and a check that a statement throws.) Each test builds its own clock, log, and alarm clock, so the tests cannot affect each other. The two static_assert lines check, when compiling, that a named clock is accepted and a temporary one is refused.

  • Time zones are ignored. sys_seconds is UTC, and the example treats it as local time. A real device would convert with a time zone (std::chrono::zoned_time and the time-zone database, which are part of C++20 but are not provided by the libstdc++ 11 and 12 libraries that this site’s GCC 11 and Clang 14 builds use; the calendar types the example needs, such as weekday and sys_days, are). The design would not change: it would be one more detail behind Clock.
  • Clock jumps. If the system time is changed (by the user, or by network time correction) while snoozed, the snooze could be longer or shorter. std::chrono::steady_clock is monotonic (it never goes backwards) and is the usual choice for measuring a duration; a real design might use it for the snooze and the system clock for the wake time. That would change the interface: Clock would need a second function (or there would be a second collaborator), and the fake would have to move both times together.
  • tick must be called often. If it is called only once an hour, the alarm rings up to an hour late. That is the main loop’s job, not the rules’.

Some rules are left open, on purpose, because the requirements do not settle them. They are worth asking the product owner about:

  • Late start. If the device is switched on at 15:00 on a weekday, it rings at once: “at or after the wake time” has no upper limit.
  • Snooze across midnight. A Friday alarm at 23:55, snoozed, rings at 00:04 on Saturday, although FR-1 says “never at the weekend”.
  • Never stopped. An alarm left ringing past midnight keeps ringing, and the next day’s alarm is not a new event. Real clocks usually stop by themselves after some minutes.
  • Stop pressed early. stop before the wake time skips today’s alarm, as FR-3’s “until the next day” says. A test checks it, along with “snooze, then stop”.
  • Values and the standard library. Do not inject std::vector, a std::string, or a Money value type. Injection is for collaborators with effects or outside state: time, files, network, hardware, randomness, other services.
  • Pure functions. A function that only computes from its arguments is already testable. Give it its inputs as parameters.
  • No second implementation and no test need. If the code is not tested in isolation and will only ever use one implementation, an interface may be ceremony (see “interfaces with one implementation” on the composition page). Time and hardware are the classic exceptions, because tests almost always need to control them.
  • Everything at once. Injecting ten collaborators into one constructor is a sign that the class has too many responsibilities, not a reason to add a container.
You gain You pay
Rules tested without waiting, for any day and time Two interfaces and two fakes to write and keep up to date
New hardware (the vibration pad) without editing the rules Readers must look at main to know which Clock is used
The rules’ file depends on nothing but the standard library A reference member, whose lifetime the programmer must get right
One place (main) shows how the program is put together main grows as the program grows (split it into small “build the X” functions if needed)
  • Putting the interface with the implementation. A Clock declared in system_clock_wrapper.hpp still makes the rules include the hardware side. Declare it where it is used.
  • Mirroring the hardware’s interface. A Bell with set_gpio_pin(int) and set_pwm_duty(int) ties the rules to one kind of speaker. Name the interface by what the rules need: ring and silence.
  • Injecting by raw pointer without saying who owns it. Bell* leaves the reader asking “may it be null? who deletes it?”. Use a reference or a unique_ptr, which answer both.
  • Binding a reference member to a temporary. See the deleted constructor above.
  • Creating collaborators inside “for convenience”. A default argument such as std::unique_ptr<Bell> bell = std::make_unique<SpeakerBell>() brings the hardware dependency straight back into the rules’ header.
  • Calling it a container problem. If wiring in main is getting long, group it into functions. Reach for a framework only if the program is truly large and the team already knows one.

The next model has a speaker and a vibration pad (NFR-2). Add one more Bell that owns two others (syntax-checked sketch, not part of the example):

// A Bell made of two Bells: ringing it rings both, silencing it silences
// both. It owns the two it is given (unique_ptr, moved in), and refuses
// a null one, so ring() and silence() never need to check.
class BothBells final : public Bell {
public:
BothBells(std::unique_ptr<Bell> first, std::unique_ptr<Bell> second)
: first_{std::move(first)}, second_{std::move(second)} {
if (!first_ || !second_) throw std::invalid_argument("BothBells needs two bells");
}
// Moving would leave the moved-from object with null bells, as with
// AlarmClock, so it is not offered.
BothBells(BothBells&&) = delete;
BothBells& operator=(BothBells&&) = delete;
// Pass each call on to both bells, in order: speaker first, then pad.
void ring() override { first_->ring(); second_->ring(); }
void silence() override { first_->silence(); second_->silence(); }
private:
std::unique_ptr<Bell> first_; // owned; never null
std::unique_ptr<Bell> second_; // owned; never null
};

main creates std::make_unique<BothBells>(std::move(speaker), std::move(pad)); AlarmClock and its tests do not change. (This shape, an object that implements an interface by passing the call on to several others of the same interface, is a simple form of the Composite pattern, covered in the patterns section.)

A different wake time at the weekend. This is a change to the rules, so it does change AlarmClock: wake_at_ becomes two times, and tick picks one by weekday instead of skipping the weekend. Neither Clock, Bell, nor any device changes, and the fake clock makes the new rule as easy to test as the old one.

Exercise: Make a class testable by injecting a clock

A café till gives 20% off drinks from 16:00 to 18:00:

class Till {
public:
// 20% off drinks from 16:00 to 18:00 (UTC, to keep it short)
[[nodiscard]] int price_cents(int list_cents) const {
using namespace std::chrono;
const auto now = floor<seconds>(system_clock::now()); // the real time, read here
const auto time = now - floor<days>(now); // time since midnight
// From 16:00 up to, but not including, 18:00.
const bool happy_hour = time >= hours{16} && time < hours{18};
// list_cents / 5 is 20%, in whole cents (integer division rounds down).
return happy_hour ? list_cents - list_cents / 5 : list_cents;
}
};
  1. Why is the happy-hour rule hard to test?
  2. Change Till so the clock is injected. Should it own the clock?
  3. Write tests for 15:59:59, 16:00:00, and 18:00:00, using a fake clock. Is that enough?
Show the explained answer

1. price_cents reads the real time itself. A test passes or fails depending on when it runs, and checking the edge at 16:00 would mean running the test at exactly 16:00.

2. One possible answer (compiled and run, not part of the example). It uses a Clock interface like this page’s. Because the till is not an alarm clock, it should not include alarm_clock.hpp to get it; once two parts of a program share an interface, it moves to a neutral header such as clock.hpp, which both include.

class Till {
public:
// The clock is borrowed, not owned: the till keeps a reference to it.
explicit Till(const Clock& clock) : clock_{clock} {}
explicit Till(const Clock&&) = delete; // no temporary clocks
[[nodiscard]] int price_cents(int list_cents) const {
using namespace std::chrono;
const sys_seconds now = clock_.now(); // the only line that changed in the rule
const auto time = now - floor<days>(now);
const bool happy_hour = time >= hours{16} && time < hours{18};
return happy_hour ? list_cents - list_cents / 5 : list_cents;
}
private:
const Clock& clock_; // not owned; must outlive the till
};

It should not own the clock. The café has one clock, which the tills, the receipts, and the opening hours all share, so it belongs to main and each till holds a reference.

3. The page’s FakeClock only has advance; for this test a set function is handier, so add one: void set(std::chrono::sys_seconds to) { now_ = to; }. Three times are not quite enough; add a fourth, 17:59:59:

// One date, and four times on it. set() jumps the fake clock straight to
// a time; each check then asks for the price of a 500-cent drink.
const sys_days day = 2026y / November / 18;
FakeClock clock{day + 15h + 59min + 59s};
Till till{clock};
LLD_CHECK(till.price_cents(500) == 500); // 15:59:59, full price
clock.set(day + 16h);
LLD_CHECK(till.price_cents(500) == 400); // 16:00:00, 20% off
clock.set(day + 17h + 59min + 59s);
LLD_CHECK(till.price_cents(500) == 400); // 17:59:59, still 20% off
clock.set(day + 18h);
LLD_CHECK(till.price_cents(500) == 500); // 18:00:00, over

The four times sit on both sides of each edge, which is where mistakes like <= for < hide: with only three, a till that ended happy hour at 17:00 would still pass. Notice how small the change was: one constructor (plus the deleted one) and one member. The rule did not change at all. (The discount uses integer division, so it rounds down: 9.99 becomes 8.00, not 7.99. That is a separate decision, which a test should pin down too.)

  • Dependency direction: the rules define the interfaces they need; details implement them. Arrows point toward the stable policy.
  • Dependency injection: a class is given its collaborators, usually in its constructor. It does not create them or look them up.
  • Inject by reference for shared collaborators that outlive the class (and delete the rvalue overload, which catches temporaries passed straight to the constructor); inject by std::unique_ptr for collaborators the class owns alone.
  • main is the composition root: one place creates the real objects and wires them. In C++, that is usually all the “framework” you need.
  • Inject things with effects or outside state (time, hardware, files, network), not values. Time is the classic case: a fake clock makes time-based rules testable without waiting.