The Dependency Inversion Principle
What you will learn on this page
Section titled “What you will learn on this page”- What the Dependency Inversion Principle (DIP) says, and what is being “inverted”.
- How to sort code into high-level policy (the rules the business cares about) and low-level detail (databases, files, networks, devices).
- Why the interface between them must be owned by the policy and written in its terms, and where that interface should live.
- How C++ modules (here, separate libraries) make the dependency direction something the build checks, not just a drawing.
- The difference between dependency inversion and dependency injection, and why you can have either without the other.
The problem
Section titled “The problem”A small online shop has an order service with three rules:
- FR-1 An order has a customer and at least one line; each line has a SKU (stock-keeping unit, the product code), a quantity of at least 1, and a price of at least 1 cent.
- FR-2 An order can be shipped unless it was cancelled.
- FR-3 An order can be cancelled unless it has shipped.
The first version was written against the company’s key-value database client: a library that stores strings under string keys. It works. Then three requests arrive in the same month:
- The company is moving to a different database next year.
- Testing the rules needs a running database server, so the tests are slow and nobody runs them.
- A warehouse tool wants to reuse the order rules, but not the database client, which it is not allowed to link.
None of these requests changes a rule. Each one, with the first version, means editing the rules.
The principle
Section titled “The principle”The Dependency Inversion Principle has two parts. In our words:
- The code that holds the policy should not depend on the code that holds the details. Both should depend on an abstraction between them.
- That abstraction should be shaped by the policy, not by the details. The details are written to fit it.
It is the “D” in SOLID.
High-level does not mean “important” or “near main”. It means
closer to the purpose of the program: the rules that would stay the
same if you changed the database, the user interface, or the hardware.
Low-level means the mechanism: how bytes reach a disk or a socket.
What is inverted is the direction of one arrow. In the first version the rules depend on the database client, because that is the order in which you think about calling things (“the service calls the store”). After inversion, the rules declare the interface they need, and the adapter, the code that knows the database, depends on the rules’ interface. Control still flows from the rules to the database at run time; only the source-code dependency turns round.
Step 1: sort what the code knows into policy and detail
Section titled “Step 1: sort what the code knows into policy and detail”Go through the first version and list each thing it knows. Then ask of each one: “would this change if we changed the database?”
| The code knows that… | Changes with the database? | Kind |
|---|---|---|
| an order needs a customer and at least one line | no | policy |
| a shipped order cannot be cancelled | no | policy |
| each new order gets an id no other order has | no | policy |
the last used id is stored under the key counter/order |
yes | detail |
an order is stored under order/<id> |
yes | detail |
| a row’s first line is the customer and its second the status | yes | detail |
kv::Store has put and get |
yes | detail |
The policy rows say what the rules need from storage, in their own words: “give me a fresh id”, “save this order”, “find the order with this id”. That list is the interface. The detail rows are how one database does it, and belong in one place that is not the rules.
Bad, good, great: where does the interface live?
Section titled “Bad, good, great: where does the interface live?”Text description of the diagram
Two parts, before and after. Before: the before module, holding an OrderService with rules, keys, and row format together, has a dashed “depends on” arrow to the kv_store module and its kv::Store. After: an orders module contains OrderService, the rules, with a dashed “uses” arrow to OrderRepository, an interface in the same module. The kv_orders module, holding KvOrderRepository with the keys and row format, has a thick “implements” arrow to OrderRepository and a dashed “depends on” arrow to the kv_store module. main, which wires the modules, has dashed “depends on” arrows to kv_orders, to OrderService, and to kv_store. No arrow leaves the orders module. A flow arrow from the Before group to the After group shows the redesign.
Diagram source (Mermaid)
flowchart TB
subgraph Before
BO["before<br/>OrderService<br/>rules + keys + row format"] -.->|depends on| BK["kv_store<br/>kv::Store"]
end
subgraph After
subgraph orders
AS["OrderService<br/>rules"] -.->|uses| AR["OrderRepository<br/>interface"]
end
AA["kv_orders<br/>KvOrderRepository<br/>keys + row format"] ==>|implements| AR
AA -.->|depends on| AK["kv_store<br/>kv::Store"]
AM["main<br/>wires the modules"] -.->|depends on| AA
AM -.->|depends on| AS
AM -.->|depends on| AK
end
Before --> AfterLook at the arrows that cross the border of the orders module in the “after” half. They all point in. That is the whole principle in one picture.
struct Order
orders module
Data members
int id;std::string customer;std::vector<OrderLine> lines;OrderStatus status;
interface (abstract class) OrderRepository
orders module; owned by the rules
Member functions
virtual int next_id() = 0;virtual void save(const Order& order) = 0;replaces an order with the same idvirtual std::optional<Order> find(int id) const = 0;
class OrderService final
orders module
Data members
OrderRepository& repository_;not owned; must outlive the service
Member functions
explicit OrderService(OrderRepository& repository);int place(std::string customer, std::vector<OrderLine> lines);throws std::invalid_argumentvoid cancel(int id);throws std::logic_error if shippedvoid ship(int id);throws std::logic_error if cancelledOrder get(int id) const;throws std::out_of_range
class KvOrderRepository final
kv_orders module; implements OrderRepository
Data members
kv::Store& store_;not owned; must outlive the repository
Member functions
explicit KvOrderRepository(kv::Store& store);int next_id() override;keeps the last id under counter/ordervoid save(const Order& order) override;throws std::invalid_argument for unstorable textstd::optional<Order> find(int id) const override;throws std::runtime_error for a corrupt row
The outline leaves out OrderLine (a SKU, a quantity, and a unit price
in cents), the OrderStatus enumeration (placed, shipped, cancelled), the
free functions total_cents and status_name, the virtual destructor, and the protected copy operations that
every interface on this site has.
The new design
Section titled “The new design”The orders module: rules and the interface they own
Section titled “The orders module: rules and the interface they own”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Plain data in the orders module's own words. Nothing here knows how or// where orders are stored.
// Where an order is in its life. A new order is placed; it then either// ships or is cancelled.enum class OrderStatus { placed, shipped, cancelled };
// One line of an order: which product (its SKU, a stock code such as// "pen-blue"), how many, and the price of one, in whole cents so that no// rounding of fractions can creep in. long long leaves room for big totals.struct OrderLine { std::string sku; int quantity; long long unit_price_cents;
// `= default` asks the compiler to write ==: two lines are equal when // every member is equal. The tests use it to compare whole orders. bool operator==(const OrderLine&) const = default;};
// A whole order. The struct holds its lines by value, in a vector: copying// an Order copies its lines too.struct Order { int id; std::string customer; std::vector<OrderLine> lines; OrderStatus status;
bool operator==(const Order&) const = default;};
// The sum of quantity * unit price over all lines.long long total_cents(const Order& order);// "placed", "shipped", or "cancelled". A string_view is a read-only view// of text; these views point at string literals, which last as long as// the program does, so the view never dangles.std::string_view status_name(OrderStatus status);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Owned by the orders module and written in its terms: orders and ids,// not keys, rows, or files. Storage adapters implement it.// An interface (an abstract class): apart from the destructor, only pure// virtual functions, `= 0`, which each storage adapter must write.// OrderService calls these through an OrderRepository&, so it never// learns which adapter it is talking to.class OrderRepository {public: // Virtual, so destroying an adapter through this base type is safe. virtual ~OrderRepository() = default;
// Returns an id that no order has used yet. virtual int next_id() = 0; // Stores the order, replacing any stored order with the same id. virtual void save(const Order& order) = 0; // The stored order, or an empty optional (std::nullopt) if there is // none with this id. "Not found" is an ordinary answer, not an error. virtual std::optional<Order> find(int id) const = 0;
protected: // Protected, so code outside the family cannot copy or assign through // OrderRepository references, which would copy only the base part // (slicing); see the idiom reference, "Interfaces". OrderRepository() = default; OrderRepository(const OrderRepository&) = default; OrderRepository& operator=(const OrderRepository&) = default;};The comment above OrderRepository is the important design decision.
It is owned by the orders module and written in its terms. Nothing in
it mentions keys, rows, strings, or a database. If a function you are
about to add to it needs a word from the database’s vocabulary, stop: the
detail is leaking in.
find returns std::optional<Order>: “no such order” is an ordinary
answer, not an error, and the caller decides what it means. The service
turns it into std::out_of_range, because for the service an unknown id
is a caller’s mistake.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The business rules for orders. It knows nothing about how orders are// stored: no keys, no text format, no database client.class OrderService final {public: // The repository is not owned and must outlive the service. // It can be any class that implements OrderRepository: the database // adapter in main, or an in-memory fake in the tests. explicit OrderService(OrderRepository& repository);
// Throws std::invalid_argument for an empty customer, no lines, or a // line with an empty SKU or a quantity or price below 1. int place(std::string customer, std::vector<OrderLine> lines); // Throws std::logic_error if the order has shipped. void cancel(int id); // Throws std::logic_error if the order was cancelled. void ship(int id); // All three throw std::out_of_range for an unknown id. // get returns a copy of the stored order. Order get(int id) const;
private: OrderRepository& repository_; // the interface, not the database};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Checks every rule first, and only then asks the repository for an id// and saves. A refused order therefore saves nothing and uses up no id.// Returns the id the repository gave the new order.int OrderService::place(std::string customer, std::vector<OrderLine> lines) { if (customer.empty()) { throw std::invalid_argument{"an order needs a customer"}; } if (lines.empty()) { throw std::invalid_argument{"an order needs at least one line"}; } for (const OrderLine& line : lines) { if (line.sku.empty() || line.quantity < 1 || line.unit_price_cents < 1) { throw std::invalid_argument{"bad order line '" + line.sku + "'"}; } } // Build the order in member order: id, customer, lines, status. // std::move hands over the parameters' text and vector instead of // copying them; customer and lines are not used again after this. const Order order{repository_.next_id(), std::move(customer), std::move(lines), OrderStatus::placed}; repository_.save(order); // how and where it is stored is the adapter's job return order.id;}
// Reads like the requirement: load the order, refuse if it has shipped,// change the status, save it back. Nothing is saved if it throws.void OrderService::cancel(int id) { // A local copy; get throws std::out_of_range if there is no such order. Order order = get(id); if (order.status == OrderStatus::shipped) { throw std::logic_error{"order " + std::to_string(id) + " has shipped"}; } order.status = OrderStatus::cancelled; // changes only the local copy... repository_.save(order); // ...so it must be saved to take effect}Compare cancel with the first version. The rule now reads as the
requirement does: get the order, refuse if it has shipped, change the
status, save. The checks in place run before next_id, so an
order the rules refuse does not use up an id (the second test checks
this). An order the adapter refuses, such as a customer name with a
newline, is refused in save, after next_id, so its id is wasted; see
the limits below.
The adapter module: the only code that knows both sides
Section titled “The adapter module: the only code that knows both sides”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Stores orders in a kv::Store. The only code that knows both the orders// module and the database client.// It translates both ways: save turns an Order into a key and a text row,// and find turns a row back into an Order. `final` means no class can// derive from it, and each `override` asks the compiler to check that the// function really replaces one declared in OrderRepository.class KvOrderRepository final : public OrderRepository {public: // The store is not owned and must outlive the repository. explicit KvOrderRepository(kv::Store& store);
// Throws std::runtime_error if the stored counter cannot be read or // has reached the largest int. int next_id() override; // Throws std::invalid_argument if the customer contains a newline, or // a SKU is empty or contains whitespace: the row format cannot hold them. void save(const Order& order) override; // Throws std::runtime_error if the stored row cannot be read. // Returns an empty optional if no row is stored under the id's key. std::optional<Order> find(int id) const override;
private: kv::Store& store_; // the database client: not owned};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One row per order, one field per line:// customer// status// sku quantity unit_price_cents (once for each order line)// For example, order 2 is stored under the key "order/2" as the text// "Lee\ncancelled\nlamp-desk 1 2999\n".//// save refuses (std::invalid_argument) what the row cannot hold, before// writing anything: a newline in the customer would start a new line, and// a space in a SKU would split it into two fields.void KvOrderRepository::save(const Order& order) { // find returns std::string::npos ("no position") when there is no '\n'. if (order.customer.find('\n') != std::string::npos) { throw std::invalid_argument{"a customer name cannot contain a newline"}; } std::ostringstream row; row << order.customer << '\n' << status_name(order.status) << '\n'; for (const OrderLine& line : order.lines) { // storable_sku (a helper above this snippet): true if the SKU is not // empty and has no whitespace, such as a space, tab, or newline. if (!storable_sku(line.sku)) { throw std::invalid_argument{"SKU '" + line.sku + "' cannot be stored"}; } row << line.sku << ' ' << line.quantity << ' ' << line.unit_price_cents << '\n'; } // put replaces any row already stored under this key, which is what // the interface promises: saving again replaces the stored order. store_.put(key_for(order.id), row.str());}
// The reverse of save: read the row and rebuild the Order, line by line.// No row means no order (an empty optional). A row that does not match// the format is not "no order" but damage, so it throws// std::runtime_error: corrupt(id) (a helper above) builds that exception// with the message "order/<id>: cannot read the stored row".std::optional<Order> KvOrderRepository::find(int id) const { const std::optional<std::string> row = store_.get(key_for(id)); if (!row) { return std::nullopt; } // An istringstream reads from a string the way std::cin reads from the // keyboard. *row is the text inside the optional. std::istringstream in{*row}; // Start with the id, an empty customer, no lines, and a status that is // overwritten below. Order order{id, {}, {}, OrderStatus::placed}; std::string status; // std::getline reads up to the next '\n' (and drops it). It reports // failure when there is nothing left to read, so a row with fewer than // two lines is corrupt. if (!std::getline(in, order.customer) || !std::getline(in, status)) { throw corrupt(id); } // parse_status (above): "shipped" becomes OrderStatus::shipped, and an // unknown word throws corrupt(id). order.status = parse_status(status, id); std::string text; // Every remaining line is one order line. The loop stops when getline // finds nothing more to read. while (std::getline(in, text)) { // Split one line, such as "pen-blue 3 120", at the spaces: >> reads // a word into sku, then a number into each of the other two. std::istringstream fields{text}; OrderLine line{}; // A stream converts to false once a read fails (a missing field, // or a word where a number should be), so this catches a bad line. if (!(fields >> line.sku >> line.quantity >> line.unit_price_cents)) { throw corrupt(id); } order.lines.push_back(std::move(line)); // move: line is not used again } return order; // wrapped in an optional automatically: "found"}How this code works: KvOrderRepository: save and find
save and find are mirror images: one writes an Order as text, the
other reads the text back into an Order.
save, for order 1 in the example run (Kim, shipped, two lines):
- Refuse a customer name with a newline in it: it would break the “one field per line” layout.
- Write the customer and the status name, each followed by
\n. - For each order line, refuse a SKU that is empty or contains
whitespace, then write
sku quantity unit_price_centsand\n. - Store the text under the key
order/1.
The row stored for order 1 is the text below. (The program’s output
prints it on one line, with / in place of each newline.)
Kimshippedpen-blue 3 120notebook-a5 1 450find(1) reads it back:
| Step | Reads | Result |
|---|---|---|
store_.get("order/1") |
the whole row | found, so carry on (not found would return std::nullopt) |
first std::getline |
Kim |
order.customer = "Kim" |
second std::getline |
shipped |
parse_status gives OrderStatus::shipped |
| loop, first pass | pen-blue 3 120 |
an OrderLine with SKU pen-blue, quantity 3, price 120 |
| loop, second pass | notebook-a5 1 450 |
an OrderLine with SKU notebook-a5, quantity 1, price 450 |
loop, third std::getline |
nothing left | the loop ends; the order is returned |
There are two different kinds of “no”. A missing row is an ordinary
answer: find returns an empty optional, and the service decides that an
unknown id is an error. A row that is there but does not fit the format
(fewer than two lines, a status word that is not a status, or a line that
does not start with a word and two numbers) is damage, so find throws
std::runtime_error. None of this, keys, text, or the two kinds of “no”,
is visible to OrderService.
Every “detail” row of Step 1 is here, and only here: the keys, the row
format, and the calls to kv::Store. The adapter also enforces what the
format cannot hold (a newline in a customer name, an empty SKU or one
with whitespace)
and refuses a row it cannot read. Those are storage rules, so they
are not in OrderService.
The name “adapter” is used because the class adapts one interface (the database client’s) to another (the one the rules asked for). The Adapter pattern page covers the idea in general.
The modules are libraries, so the build checks the direction
Section titled “The modules are libraries, so the build checks the direction”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
# Each folder is a module with its own library. A module's sources can# include only its own headers and those of the libraries it links to,# so the target_link_libraries lines below are the dependency graph.
# Low-level detail: the (simulated) database client. Depends on nothing.add_library(principles_dip_kv STATIC kv_store/kv_store.cpp)target_include_directories(principles_dip_kv PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/kv_store)
# High-level policy: the order rules and the interface they own.# Depends on nothing either.add_library(principles_dip_orders STATIC orders/order.cpp orders/order_service.cpp)target_include_directories(principles_dip_orders PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/orders)
# The adapter: the only module that depends on both.add_library(principles_dip_kv_orders STATIC kv_orders/kv_order_repository.cpp)target_include_directories(principles_dip_kv_orders PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/kv_orders)target_link_libraries(principles_dip_kv_orders PUBLIC principles_dip_orders principles_dip_kv)
# Before: the order rules depend directly on the database client.add_library(principles_dip_before STATIC before/before.cpp)target_include_directories(principles_dip_before PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/before)target_link_libraries(principles_dip_before PUBLIC principles_dip_orders principles_dip_kv)
lld_add_example(principles_dip SOURCES main.cpp EXPECTED_OUTPUT expected_output.txt)target_link_libraries(principles_dip PRIVATE principles_dip_kv_orders principles_dip_before)
# The rules are tested without the database client or the adapter.lld_add_test(principles_dip_orders_tests SOURCES test_order_service.cpp)target_link_libraries(principles_dip_orders_tests PRIVATE principles_dip_orders)
lld_add_test(principles_dip_kv_orders_tests SOURCES test_kv_order_repository.cpp)target_link_libraries(principles_dip_kv_orders_tests PRIVATE principles_dip_kv_orders principles_dip_before)Each folder is its own static library with its own include directory.
The orders library links nothing, so a file in orders/ that writes
#include "kv_store.hpp" fails to compile: the header is not on its
include path. (We checked this by hand with g++; no build test enforces
it. A relative path such as #include "../kv_store/kv_store.hpp" would
get round it, so code review or a tool still has to catch that.) The
dependency diagram above is therefore not only a drawing; it is
what the build allows.
The two test executables show the payoff. principles_dip_orders_tests
links only the orders library: the rules are tested with no database
client and no adapter in the program at all.
main: the composition root
Section titled “main: the composition root”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// main is the only place that knows every module.// Declared in dependency order. Local variables are destroyed in the// reverse order, so the service goes first, then the repository, then// the store: nothing is destroyed while something still refers to it.kv::Store store; // the database clientKvOrderRepository repository{store}; // the adapter; refers to storeOrderService service{repository}; // the rules; refer to repositorymain is the only code that knows every module; it is the
composition root. It
creates the objects in dependency order, so they are destroyed in reverse:
the service first, then the adapter, then the store. Each one refers to
the next without owning it, and each outlives the objects that refer to
it.
Why each choice
Section titled “Why each choice”| Choice | Why | What it costs |
|---|---|---|
OrderRepository lives in the orders module |
The rules own what they need; they compile and link alone | The orders team decides the interface; the storage side must adapt |
It speaks in Order and ids |
Any database can implement it; the rules never parse a row | Each adapter converts between orders and its own format |
| Three operations, from Step 1 | Only what the rules use (see ISP) | A new query (say, orders by customer) means adding a function and implementing it in each adapter |
find returns std::optional |
“Not found” is a normal result; the service decides it is an error | Callers must check |
| An adapter in its own module | The only code that depends on both sides; it can be replaced without touching the rules | One more library and one more class |
Non-owning references, objects owned by main |
Lifetimes are plain: created in order, destroyed in reverse | The service and adapter cannot be assigned (they hold references), and must not outlive what they refer to |
| One library per module | The build rejects an ordinary include in the wrong direction | More CMake; a small program may not need it |
Dependency inversion is not dependency injection
Section titled “Dependency inversion is not dependency injection”The two names sound alike and are often confused. They answer different questions:
| Dependency inversion | Dependency injection | |
|---|---|---|
| Question it answers | Which module owns the interface, and which way do source dependencies point? | How does an object get the collaborators it uses? |
| When it is decided | When you design modules and write #include and link lines |
When the program runs (or when main is written) |
| What you see in C++ | Where the interface’s header is, and the target_link_libraries lines |
A constructor parameter such as OrderRepository& |
You can have either one without the other:
- Injection without inversion. The first version:
kv::Store&is injected through the constructor, but it is the concrete database client, owned by the database module. - Inversion without injection. The orders module owns
OrderRepository, but the program picks the implementation at link time: the orders library declares a functionOrderRepository& order_repository();, and whichever adapter library is linked into the program defines it. The direction is right, but the service cannot be given a fake in a test without building a separate test program, and the program can have only one implementation. - Both. The new design: the rules own the interface, and
maininjects the adapter.
Usually you want both. Inversion makes the right interface exist in the right place; injection gets an implementation to the object that needs it.
Where should an interface live?
Section titled “Where should an interface live?”This is the practical question DIP answers. The rule of thumb: put the interface next to the code that uses it, not the code that implements it.
| Situation | Where the interface goes |
|---|---|
| One high-level module needs a detail (orders needs storage) | In that module (orders/order_repository.hpp) |
| Several high-level modules need different things from one detail | One role interface in each module (see ISP); one adapter can implement several |
| Several modules need the same thing (a logger, a clock) | A small, separate module with only the interface, which they all depend on |
A standard abstraction already says it (std::ostream&, a callback) |
Use it; do not wrap a standard interface in your own for its own sake |
| You are writing a library for others to plug into | In the library: it is the high-level side, and its users write the adapters |
before: refused: order 1 has shipped order 1 for Kim: 2 line(s), 8.10, shipped order 2 for Lee: 1 line(s), 29.99, cancelledafter: refused: order 1 has shipped order 1 for Kim: 2 line(s), 8.10, shipped order 2 for Lee: 1 line(s), 29.99, cancelled stored rows: counter/order: 2 order/1: Kim / shipped / pen-blue 3 120 / notebook-a5 1 450 order/2: Lee / cancelled / lamp-desk 1 2999The old and new versions give the same results for the same morning: two orders, one shipped and then refused a cancel, one cancelled. The stored rows show what the adapter wrote; the orders module never sees these strings.
The rules’ tests use a fake repository that speaks the orders module’s language:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
namespace {// An in-memory repository for tests. It is short because the interface// speaks the orders module's language.// It keeps orders in a std::map from id to Order, hands out ids 1, 2, 3,// ..., and counts how many times save was called, so a test can check// that a refused order saved nothing.class MemoryOrderRepository final : public OrderRepository {public: // ++last_id_ adds one first and then returns the new value: 1, 2, 3... int next_id() override { return ++last_id_; } void save(const Order& order) override { // Adds the order under its id, or replaces the one already there. // The map keeps its own copy of the order. orders_.insert_or_assign(order.id, order); ++saves_; } std::optional<Order> find(int id) const override { // map::find returns an iterator to the (id, order) pair, or end() // if the id is not there. found->second is the Order in the pair. // The two sides of ?: must have one type, hence the explicit // std::optional<Order>{...}, which copies the stored order. const auto found = orders_.find(id); return found == orders_.end() ? std::nullopt : std::optional<Order>{found->second}; } int saves() const { return saves_; }
private: std::map<int, Order> orders_; int last_id_ = 0; int saves_ = 0;};} // namespaceVerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; LLD_CHECK_EQ(actual, expected) records one if// the two values differ, and shows both; 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. Each test builds its// own fake repository and service, so no test sees another's orders.
// Two orders get different ids, and the first can be read back as it was// placed: Kim, status placed, and 3 x 120 = 360 cents.LLD_TEST(placing_stores_the_order_with_a_fresh_id) { MemoryOrderRepository repository; OrderService service{repository}; const int first = service.place("Kim", {{"pen-blue", 3, 120}}); const int second = service.place("Lee", {{"lamp-desk", 1, 2999}}); LLD_CHECK(first != second); const Order stored = service.get(first); LLD_CHECK(stored.customer == "Kim"); LLD_CHECK(stored.status == OrderStatus::placed); LLD_CHECK_EQ(total_cents(stored), 360);}
// Four orders the rules refuse: no customer, no lines, a quantity of 0,// and an empty SKU. None of them reached save, and none took an id, so// the next good order is order 1.LLD_TEST(a_refused_order_is_not_saved) { MemoryOrderRepository repository; OrderService service{repository}; LLD_CHECK_THROWS(service.place("", {{"pen-blue", 1, 120}}), std::invalid_argument); LLD_CHECK_THROWS(service.place("Kim", {}), std::invalid_argument); LLD_CHECK_THROWS(service.place("Kim", {{"pen-blue", 0, 120}}), std::invalid_argument); LLD_CHECK_THROWS(service.place("Kim", {{"", 1, 120}}), std::invalid_argument); LLD_CHECK_EQ(repository.saves(), 0); // The refused orders did not use up any ids. LLD_CHECK_EQ(service.place("Kim", {{"pen-blue", 1, 120}}), 1);}
// The two status rules, and proof that a refused change left the stored// status as it was.LLD_TEST(shipped_orders_cannot_be_cancelled_and_cancelled_ones_cannot_ship) { MemoryOrderRepository repository; OrderService service{repository}; const int shipped = service.place("Kim", {{"pen-blue", 1, 120}}); const int cancelled = service.place("Lee", {{"lamp-desk", 1, 2999}}); service.ship(shipped); service.cancel(cancelled); LLD_CHECK_THROWS(service.cancel(shipped), std::logic_error); LLD_CHECK_THROWS(service.ship(cancelled), std::logic_error); LLD_CHECK(service.get(shipped).status == OrderStatus::shipped); LLD_CHECK(service.get(cancelled).status == OrderStatus::cancelled);}
// An empty repository: every operation on id 42 throws std::out_of_range.LLD_TEST(unknown_ids_are_refused) { MemoryOrderRepository repository; OrderService service{repository}; LLD_CHECK_THROWS(service.get(42), std::out_of_range); LLD_CHECK_THROWS(service.cancel(42), std::out_of_range); LLD_CHECK_THROWS(service.ship(42), std::out_of_range);}The test double is
a std::map, an id counter, and the three overrides. It also counts
saves, so the second test can check that a refused order writes
nothing.
The adapter has its own tests against the database client, including one that runs the old and new designs side by side and checks that they store exactly the same rows:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// These tests use the real adapter on a kv::Store (the in-memory stand-in// for the database client). LLD_TEST, LLD_CHECK, LLD_CHECK_EQ, and// LLD_CHECK_THROWS are the same test macros as in the rules' tests.
// Save an order with two lines and a shipped status, then find it: the// Order that comes back equals the one saved (== compares every member,// lines included). An id that was never saved finds nothing.LLD_TEST(an_order_survives_a_round_trip) { kv::Store store; KvOrderRepository repository{store}; const Order order{7, "Kim Park", {{"pen-blue", 3, 120}, {"notebook-a5", 1, 450}}, OrderStatus::shipped}; repository.save(order); LLD_CHECK(repository.find(7) == order); LLD_CHECK(!repository.find(8).has_value());}
// The id counter is kept in the store, not in the adapter object.LLD_TEST(ids_continue_after_a_restart) { kv::Store store; // The inner braces make a scope: first_run is destroyed at the closing // brace, as if the program had stopped. The store lives on. { KvOrderRepository first_run{store}; LLD_CHECK_EQ(first_run.next_id(), 1); LLD_CHECK_EQ(first_run.next_id(), 2); } KvOrderRepository second_run{store}; // same database, new process LLD_CHECK_EQ(second_run.next_id(), 3);}
// Saving a customer with a newline, or a SKU with a space, is refused.// Then the test writes bad data straight into the store, as a damaged// database might hold: a row whose status "lost" is not a status, and a// counter that is not a number. Reading either throws std::runtime_error.LLD_TEST(what_the_row_format_cannot_hold_is_refused) { kv::Store store; KvOrderRepository repository{store}; LLD_CHECK_THROWS(repository.save({1, "Kim\nPark", {{"pen", 1, 1}}, OrderStatus::placed}), std::invalid_argument); LLD_CHECK_THROWS(repository.save({1, "Kim", {{"blue pen", 1, 1}}, OrderStatus::placed}), std::invalid_argument); store.put("order/2", "Kim\nlost\n"); LLD_CHECK_THROWS(repository.find(2), std::runtime_error); store.put("counter/order", "many"); LLD_CHECK_THROWS(repository.next_id(), std::runtime_error);}
// The same order placed and shipped through the old service and the new// one, each with its own store. Afterwards both stores hold the same keys// (keys("") lists every key) and, key by key, the same text.LLD_TEST(the_new_design_stores_the_same_rows_as_the_old_one) { kv::Store old_store; before::OrderService old_service{old_store}; kv::Store new_store; KvOrderRepository repository{new_store}; OrderService new_service{repository};
const int old_id = old_service.place("Kim", {{"pen-blue", 3, 120}}); const int new_id = new_service.place("Kim", {{"pen-blue", 3, 120}}); old_service.ship(old_id); new_service.ship(new_id); LLD_CHECK(old_store.keys("") == new_store.keys("")); for (const std::string& key : new_store.keys("")) { LLD_CHECK(old_store.get(key) == new_store.get(key)); }}ids_continue_after_a_restart creates a second adapter on the same store,
as a program that restarts against the same database would. The id
counter lives in the database, not in the adapter object, so ids do not
repeat.
Limits of the example
Section titled “Limits of the example”- The database is a
std::map. A real client can fail (a timeout, a lost connection); the adapter would turn those failures into an error the rules understand, and the interface’s comments would say whatsavethrows. next_idandsaveare separate calls, so a crash between them wastes an id, and two programs sharing a database could race on the counter. An order that the adapter refuses insavealso wastes the id thatnext_idgave it. A real database would generate ids itself or offer a transaction; the Repository and Unit of Work page covers this.- Cancelling reads the order, changes it, and saves it. Two people cancelling and shipping at the same moment could overwrite each other’s change. The example has one user at a time.
mainuses a function template,run_morning, to run the same steps on both versions. That is a convenience for the comparison, not part of the design.
C++ notes
Section titled “C++ notes”- Headers are the dependency. In C++, “module A depends on module B”
shows up as A’s files including B’s headers and A’s library linking
B’s. Reading the
#includelines of a high-level file is the quickest DIP check there is. - Do not let detail types into the interface. An interface that
returns a database result set, or takes a
kv::Store&, makes every user include the detail’s header. Return your own types (Order,std::optional<Order>). - Templates can invert dependencies too. A template
OrderService<Repository>with a concept for the three operations gives the same direction with no virtual calls. The cost is that the rules move into a header and every user recompiles when they change. For storage, whose calls are far slower than a virtual call, the virtual interface is the simpler choice.
When not to invert
Section titled “When not to invert”- A small program or script. A 200-line tool that reads one file and prints a summary does not need a repository interface and an adapter module. Write it directly; extract an interface when a second implementation or a test needs it.
- Stable, standard dependencies. Depending on
std::string,std::vector, orstd::mapis not a DIP problem. They will not change under you. Invert dependencies on things that are volatile (likely to change) or slow and external (databases, networks, devices, time). - Inside a module. Classes in the same module that change together can depend on each other directly. DIP matters most at the borders between modules.
Trade-offs
Section titled “Trade-offs”| You gain | You pay |
|---|---|
| Rules that compile, link, and test with nothing else | An interface, an adapter, and a module boundary to maintain |
| Changing the database means writing a new adapter, not editing the rules | The adapter converts between the rules’ types and the database’s, which is extra code |
| The direction is visible in includes and link lines, and the build can check it | Someone has to design the interface well; a poor one is copied into every adapter |
| Other programs (the warehouse tool) can reuse the rules | A reader must look in two places to see how an order is stored |
Common mistakes
Section titled “Common mistakes”- Putting the interface in the detail’s module. The “better” design above. It is testable, but it is not inverted.
- An interface that mirrors the database.
put(key, value),execute(sql), or functions that return rows make the rules speak the database’s language. Write the interface from the rules’ side. - Business rules in the adapter. “Do not save a cancelled order that
has shipped” in
KvOrderRepository::savewould be lost when the adapter is replaced. Adapters translate; rules stay in the rules. - An interface for every class. DIP is for borders where the detail is volatile or external. An interface in front of a value type or a helper in the same module only adds a layer.
- Calling it “inversion” because there is a constructor parameter. That is injection; check where the interface lives.
When a requirement changes
Section titled “When a requirement changes”The company moves to a relational database. Write a new adapter
module, sql_orders, with a SqlOrderRepository that implements
OrderRepository, and change the three lines in main. OrderService
and its tests do not change. Write the same behaviour tests for both
adapters (a round trip, an unknown id, ids that continue after a
restart), so you can see they behave the same. (The side-by-side test in
this example compares the old and new designs, not two adapters.)
The shop needs a page listing a customer’s orders. The rules now need
a new operation, so the interface grows in the rules’ terms:
virtual std::vector<Order> find_by_customer(std::string_view customer) const = 0;. Each adapter implements it in its own way (the key-value
adapter might keep an index under customer/<name>).
Reads are slow, and the shop wants a cache. Write a
CachingOrderRepository that implements OrderRepository, holds another
OrderRepository&, and keeps recent orders in memory. Neither the rules
nor the key-value adapter change; main puts the cache between them.
This is the Decorator pattern, covered later.
Exercise
Section titled “Exercise”Exercise: Decide where an interface should live
A program sends a weekly sales report. It has three modules:
- reports: builds a
Report(a title and rows of figures) from the week’s sales. This is the policy. - smtp: a third-party client for sending email:
smtp::Clientwithconnect(host, port),send(from, to, mime_message), andquit(). - app:
main.
Today reports::Weekly::send() builds the report, formats it as a MIME
email, and calls smtp::Client directly.
The team now wants to test the report without an email server, and may later post reports to a chat channel instead of email.
- Which module should own the interface the report sender uses?
- Sketch the interface. What must it not mention?
- Where does the class that uses
smtp::Clientgo, and what does it depend on? - A second module, alerts, also needs to send messages to people. Where does its interface go?
Show the explained answer
1. The reports module. It is the high-level side, and the interface describes what the report needs (“deliver this report”), not what the email library offers.
2. For example:
interface (abstract class) ReportDelivery
in reports; owned by the report rules
Member functions
virtual void deliver(const Report& report) = 0;throws if delivery fails
class EmailReportDelivery final
in a new module, reports_email; implements ReportDelivery
Data members
smtp::Client& client_;not ownedstd::string recipients_;
Member functions
void deliver(const Report& report) override;formats MIME and sends
It must not mention hosts, ports, MIME, or smtp:: types. Who receives
the report is chosen when the adapter is built (in main), so it is not
a parameter either, unless the rules decide who receives it.
3. In a new adapter module (here reports_email) that depends on
both reports and smtp. Formatting the MIME message is an email
detail, so it moves there too. A chat adapter would be another module,
reports_chat. The test uses a fake ReportDelivery that stores the
report it was given.
reports::Weekly changes too: it takes a ReportDelivery& in its
constructor instead of using smtp::Client. Connecting to and leaving
the mail server (connect and quit) is the adapter’s business, or
main’s if it owns the client; the report rules never see it.
4. It depends on what alerts needs. If it needs something different (say, “notify the on-call person with a short message”), it gets its own role interface in the alerts module, and one adapter class can implement both interfaces. If both modules really need the same thing, put that one interface in a small shared module that both depend on. Do not put it in reports just because it was there first: then alerts would depend on reports for no reason.
Summary
Section titled “Summary”- DIP: high-level policy and low-level detail both depend on an abstraction, and the abstraction is owned by the policy and written in its terms.
- What is inverted is the source-code dependency. Control still flows from the rules to the database.
- Sort what the code knows into policy and detail; the policy’s needs become the interface, and the detail moves into an adapter.
- In C++, dependency is visible in
#includeand link lines. Separate libraries let the build reject a dependency in the wrong direction. - Inversion decides where interfaces live; injection gets implementations to objects. You usually want both, and having one does not give you the other.
- Put an interface next to the code that uses it. Invert at module borders with volatile or external details, not everywhere.