Composition over inheritance, and programming to interfaces
What you will learn on this page
Section titled “What you will learn on this page”- What “composition over inheritance” and “programming to an interface” mean, and why they are usually taught together.
- How to find the variation point: the one part of a problem that really has several behaviours, and the parts that only look like it.
- Why one subclass per combination grows out of control, and how small composed objects avoid it.
- How to design an interface from the implementations you actually have.
- Who owns what in a composed design, written down in C++ types.
- When an interface is not worth it, including the common case of an interface with a single implementation.
The problem
Section titled “The problem”An online shop sells household goods. At checkout, the customer sees the price of shipping for each option and picks one.
- FR-1 Post. 4.50 up to 2 kg, plus 1.50 for each started kilogram above that. Twice the price abroad.
- FR-2 Courier. 9.90 up to 10 kg, plus 0.80 for each started kilogram above that. 12.00 extra abroad.
- FR-3 Collect in store. Free, but only for customers at home.
- FR-4 Offers. Post is free when the goods cost at least 50.00. The marketing team adds or changes an offer every few months, and wants to use offers with any way of shipping.
- FR-5 The customer can change the shipping choice at checkout, as often as they like, without losing the basket.
The shop also knows that new carriers appear about once a year.
Two ideas
Section titled “Two ideas”| Idea | What it means | What it is not |
|---|---|---|
| Composition over inheritance | Build varying behaviour by giving an object parts that can be swapped or combined, instead of creating a subclass for each behaviour. | “Never use inheritance.” Implementing an interface is inheritance, and it is fine. |
| Programming to an interface | Code that uses a behaviour depends on a small description of what it does (an interface), not on a particular class that does it. | “Put an interface in front of every class.” Most classes do not need one. |
They go together because composition needs something to compose. If an order is to be combined with “any way of shipping”, there must be a type that means “a way of shipping”. That type is the interface, and the code that works with “any” of them is programming to it.
Composition in this page’s sense means an object gets behaviour from objects it holds or is given, rather than from a base class. Inheriting an interface (promising to provide some functions) is different from inheriting an implementation (reusing a base class’s code and data). The first is the normal way to implement an interface in C++. The second is what composition replaces.
Step 1: find the variation point
Section titled “Step 1: find the variation point”A variation point is a place where the program must support several behaviours that change independently of the code around them. Not everything that differs is one. List what differs in the problem, and ask how each thing varies:
| What differs | How many now | How it changes | What it is |
|---|---|---|---|
| the carrier’s tariff | 3 | a new carrier about once a year; tariffs change | a variation point: behaviour |
| home or abroad | 2 | never; it is a fact about the order | data on the order |
| offers | 1 now | every few months, combined with any carrier | a variation point that wraps another |
| the items in the basket | any number | the customer adds and removes them | data, owned by the order |
| how weight rounds up to started kilograms | 1 | not expected to change | a plain function |
Two rules come out of this table:
- A difference in data is not a new type. “Abroad” changes the price,
and each tariff treats it differently (post doubles, courier adds 12.00,
collect in store is not available). But each tariff handles it in one
line, so it needs no class of its own. It is a
boolthat each tariff reads. - Things that combine should be separate objects. Offers apply on top of any carrier. If carriers and offers are both subclasses of one class, every combination needs its own class.
Bad, good, great: where does shipping live?
Section titled “Bad, good, great: where does shipping live?”Text description of the diagram
Two parts, before and after. Before: ExpressOrder, InternationalOrder, and FreeShippingOrder each have a thick “is a” arrow to Order (standard post, at home), and InternationalExpressOrder has a thick “is a” arrow to ExpressOrder. After: ShippingOptions has a solid arrow labelled “owns 0..*” to the ShippingRate interface. PostRate, CourierRate, CollectInStore, and FreeAbove each have a thick “is a” arrow to ShippingRate. FreeAbove also has a solid arrow labelled “owns 1” to ShippingRate: it holds the rate it wraps. The quote function has dashed “uses” arrows to ShippingRate and to Order, which holds the items and whether the order goes abroad. Order has no arrows to anything about shipping. An arrow from the Before group to the After group shows the refactoring.
Diagram source (Mermaid)
flowchart TB
subgraph Before
O["Order<br/>post, at home"]
E["ExpressOrder"] ==>|is a| O
I["InternationalOrder"] ==>|is a| O
F["FreeShippingOrder"] ==>|is a| O
IE["InternationalExpressOrder"] ==>|is a| E
end
subgraph After
SO["ShippingOptions"] -->|"owns 0..*"| R["ShippingRate<br/>interface"]
P["PostRate"] ==>|is a| R
C["CourierRate"] ==>|is a| R
CS["CollectInStore"] ==>|is a| R
FA["FreeAbove"] ==>|is a| R
FA -->|owns 1| R
QF["quote()"] -.->|uses| R
QF -.->|uses| OR["Order<br/>items, home or abroad"]
end
Before --> AfterThe new design
Section titled “The new design”interface (abstract class) ShippingRate
one way of charging for delivery
Member functions
virtual ~ShippingRate() = default;virtual std::optional<int> cost_cents(const Parcel& parcel) const = 0;empty: cannot ship
class PostRate final
implements ShippingRate; no data
Member functions
std::optional<int> cost_cents(const Parcel& parcel) const override;
class CourierRate final
implements ShippingRate; no data
Member functions
std::optional<int> cost_cents(const Parcel& parcel) const override;
class CollectInStore final
implements ShippingRate; empty abroad
Member functions
std::optional<int> cost_cents(const Parcel& parcel) const override;
class FreeAbove final
implements ShippingRate by wrapping another rate
Data members
int threshold_cents_;std::unique_ptr<const ShippingRate> inner_;owned; never null
Member functions
FreeAbove(int threshold_cents, std::unique_ptr<const ShippingRate> inner);throws if null or threshold < 0FreeAbove(FreeAbove&&) = delete;a moved-from offer would hold no ratestd::optional<int> cost_cents(const Parcel& parcel) const override;
struct Parcel
what a rate may know about an order
Data members
int weight_grams = 0;int goods_cents = 0;bool abroad = false;
class Order
items and destination; no shipping data
Data members
std::vector<Item> items_;bool abroad_;
Member functions
explicit Order(bool abroad);void add(const Item& item);throws for bad quantity, price, or weightint goods_cents() const;int weight_grams() const;Parcel parcel() const;
class ShippingOptions
owns the rates the shop offers, by name
Data members
std::map<std::string, std::unique_ptr<const ShippingRate>, std::less<>> rates_;
Member functions
void add(std::string name, std::unique_ptr<const ShippingRate> rate);throws if null or takenconst ShippingRate& find(std::string_view name) const;throws std::out_of_rangestd::vector<std::string> names() const;
struct Quote
the result of pricing one order with one rate
Data members
int goods_cents = 0;int shipping_cents = 0;
Member functions
int total_cents() const;
The interface. It has one job and one function, and it is written so
that a ShippingRate can never be sliced out of a rate (the protected
special members are
explained in inheritance and interfaces):
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The variation point: one way of charging for delivery. Code that quotes// a price depends on this, never on a particular carrier.// It is an interface: one pure virtual function and no data. Each way of// shipping is a class derived from it, and callers hold a// `const ShippingRate&` without knowing which class is behind it.class ShippingRate {public: // Virtual, so a rate owned through std::unique_ptr<const ShippingRate> // is destroyed as its real class (PostRate, FreeAbove, ...). virtual ~ShippingRate() = default;
// The cost in cents, or empty if this rate cannot ship the parcel. // `= 0` makes it pure virtual: ShippingRate has no body for it, every // concrete rate must provide one (with `override`), and nobody can make // a plain ShippingRate object. `const`: asking for a price never // changes the rate. The result is std::optional<int>, so "cannot ship" // is a separate answer from "costs 0". [[nodiscard]] virtual std::optional<int> cost_cents(const Parcel& parcel) const = 0;
protected: // Only derived classes may copy or move the base part (no slicing). // Slicing is copying only the ShippingRate part of an object: for // example, assigning one rate to another through two ShippingRate& // references would copy the base part and silently skip the rest. With // these protected, code outside the family cannot write such a copy. ShippingRate() = default; ShippingRate(const ShippingRate&) = default; ShippingRate& operator=(const ShippingRate&) = default; ShippingRate(ShippingRate&&) = default; ShippingRate& operator=(ShippingRate&&) = default;};The carriers. Each one is a few lines and knows only its own tariff:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each carrier is one small class. Being abroad is data in the Parcel, not// another class: each rate decides what it means for its own price.// `final` means no class may derive from these; `override` asks the// compiler to check that the function really replaces the interface's// cost_cents. None of them has data members, so they are tiny and can be// shared freely.
// Post: 4.50 up to 2 kg, plus 1.50 per started kg above; doubled abroad.class PostRate final : public ShippingRate {public: [[nodiscard]] std::optional<int> cost_cents(const Parcel& parcel) const override;};
// Courier: 9.90 up to 10 kg, plus 0.80 per started kg above; plus 12.00 abroad.class CourierRate final : public ShippingRate {public: [[nodiscard]] std::optional<int> cost_cents(const Parcel& parcel) const override;};
// Returns 0 at home and an empty optional ("cannot ship") abroad.class CollectInStore final : public ShippingRate { // free, but only at homepublic: [[nodiscard]] std::optional<int> cost_cents(const Parcel& parcel) const override;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same tariffs as the old subclasses, now reading only the Parcel.// started_kg_above(grams, limit) counts whole or part kilograms above the// limit: 2300 g is 1 kg above 2000 g. Returning a plain int from a function// whose result type is std::optional<int> fills the optional with it.std::optional<int> PostRate::cost_cents(const Parcel& parcel) const { const int home = 450 + 150 * started_kg_above(parcel.weight_grams, 2000); // `?:` reads "if abroad, twice the home price, otherwise the home price". return parcel.abroad ? 2 * home : home;}
std::optional<int> CourierRate::cost_cents(const Parcel& parcel) const { const int home = 990 + 80 * started_kg_above(parcel.weight_grams, 10000); return parcel.abroad ? home + 1200 : home;}
// The rate that showed the interface needed std::optional: abroad it cannot// ship at all, which is different from shipping for free.std::optional<int> CollectInStore::cost_cents(const Parcel& parcel) const { if (parcel.abroad) return std::nullopt; // an empty optional: not available return 0;}The offer. This is composition: FreeAbove is a ShippingRate, so
it can be used anywhere a rate can, and it has a ShippingRate, the
one it wraps. Because it only talks to the inner rate through the
interface, it works with every carrier, including carriers that do not
exist yet:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Composition: an offer wraps any other rate instead of subclassing it.// FreeAbove is a ShippingRate (so it can go anywhere a rate can) and has a// ShippingRate inside it (the one it makes free). It never names a// carrier, so it works with PostRate, CourierRate, or a rate written later.class FreeAbove final : public ShippingRate {public: // Throws std::invalid_argument if `inner` is null or the threshold is negative. // `inner` is a std::unique_ptr: the caller hands over ownership, usually // as std::make_unique<PostRate>(), and the offer destroys it later. FreeAbove(int threshold_cents, std::unique_ptr<const ShippingRate> inner);
// Not copyable (it owns its inner rate) and not movable: a moved-from // offer would hold no rate. Hold offers through std::unique_ptr instead. // `= delete` forbids the move operations; declaring them also stops the // compiler from writing copy operations, so FreeAbove cannot be copied. FreeAbove(FreeAbove&&) = delete; FreeAbove& operator=(FreeAbove&&) = delete;
// Free when the goods reach the threshold, if `inner` can ship at all. [[nodiscard]] std::optional<int> cost_cents(const Parcel& parcel) const override;
private: int threshold_cents_; // goods value, in cents, from which delivery is free std::unique_ptr<const ShippingRate> inner_; // owned; never null};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// std::move(inner) passes ownership of the wrapped rate from the parameter// to the member inner_; a unique_ptr cannot be copied, only moved. The// checks then look at the members. If one throws, the half-built offer is// destroyed and inner_ deletes the wrapped rate, so nothing leaks.FreeAbove::FreeAbove(int threshold_cents, std::unique_ptr<const ShippingRate> inner) : threshold_cents_{threshold_cents}, inner_{std::move(inner)} { if (!inner_) throw std::invalid_argument("FreeAbove needs a rate to wrap"); if (threshold_cents_ < 0) throw std::invalid_argument("threshold must not be negative");}
// Asks the wrapped rate first, then decides whether to waive the price.std::optional<int> FreeAbove::cost_cents(const Parcel& parcel) const { // A virtual call through the interface: runs PostRate's, CourierRate's, // or any other rate's cost_cents, whichever inner_ really points to. const std::optional<int> normal = inner_->cost_cents(parcel); if (!normal) return std::nullopt; // an offer cannot make a rate available // *normal reads the int inside the optional; safe, as it is not empty. // At or above the threshold the delivery is free, otherwise full price. return parcel.goods_cents >= threshold_cents_ ? 0 : *normal;}How this code works: FreeAbove: who owns what, and how a price is found
Building one. The example program writes
std::make_unique<FreeAbove>(5000, std::make_unique<PostRate>()).
- The inner
std::make_unique<PostRate>()creates aPostRateon the heap and returns thestd::unique_ptrthat owns it. - That pointer is moved into the constructor’s
innerparameter, and then, withstd::move(inner), into the memberinner_. From now on the offer owns thePostRate; when the offer is destroyed, so is thePostRate. - The constructor checks that
inner_is not null and the threshold is not negative, and throwsstd::invalid_argumentotherwise. - The outer
std::make_unique<FreeAbove>(...)returns a pointer that owns the offer, andoptions.addtakes that pointer into its map.
Asking for a price. cost_cents(parcel) does two things in order:
- It asks the wrapped rate, through the interface.
inner_->cost_centsrunsPostRate’s version here, butFreeAbovenever namesPostRate, so the same code works for any rate. - If the wrapped rate gave no price, the offer gives none either. If it did, the offer compares the goods value with the threshold and returns 0 or the normal price.
Worked examples, with the example basket (65.00 of goods, 2300 g):
| Option | Where | Wrapped rate says | Goods ≥ threshold? | Result |
|---|---|---|---|---|
| post, free from 50.00 | home | 450 + 150 × 1 = 600 | 6500 ≥ 5000: yes | 0 |
| post, free from 50.00 | abroad | 2 × 600 = 1200 | 6500 ≥ 5000: yes | 0 |
| courier, free from 80.00 | home | 990 | 6500 ≥ 8000: no | 990 |
| collect in store, free from 0 (test only) | abroad | empty | not asked | empty |
The last row is from the test free_above_wraps_any_rate: the offer
cannot turn “cannot ship” into “free”.
The order, and the function that prices it. quote takes a
const ShippingRate&, not a const PostRate&. That is what “programming
to an interface” looks like in a signature:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// An order knows its items and where it goes. It does not know how it will// be shipped, so the customer can change that at any time.// There are no subclasses and no virtual functions: one Order type for// every way of shipping.class Order {public: // abroad true: the order goes to another country. `explicit` stops a // bool from quietly turning into an Order. explicit Order(bool abroad) : abroad_{abroad} {}
// Throws std::invalid_argument for a quantity below 1 or a negative // price or weight. void add(const Item& item);
// Sums over the items, each price or weight times its quantity. [[nodiscard]] int goods_cents() const; [[nodiscard]] int weight_grams() const; // The three facts a rate needs, copied into a small Parcel value. The // braces fill Parcel's fields in order: weight, goods value, abroad. // A rate gets this, not the Order, so it cannot see or change the items. [[nodiscard]] Parcel parcel() const { return {weight_grams(), goods_cents(), abroad_}; }
private: std::vector<Item> items_; bool abroad_;};
// A price for one order with one rate: the goods, the shipping, and their// sum. A plain value that holds no references to the order or the rate.struct Quote { int goods_cents = 0; int shipping_cents = 0; [[nodiscard]] int total_cents() const { return goods_cents + shipping_cents; }};
// Programs to the interface: works with every rate, including ones not// written yet. Empty if the rate cannot ship this order.// Both arguments are borrowed for the call only (const references); the// returned Quote is a copy of the numbers.[[nodiscard]] std::optional<Quote> quote(const Order& order, const ShippingRate& rate);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Prices one order with one rate. It does not know which rate it was given:// rate.cost_cents is a virtual call that runs the real class's version.std::optional<Quote> quote(const Order& order, const ShippingRate& rate) { const Parcel parcel = order.parcel(); const std::optional<int> shipping = rate.cost_cents(parcel); // An empty optional converts to false: the rate cannot ship this order, // so there is no quote either. if (!shipping) return std::nullopt; // *shipping is the cost inside the optional, safe to read after the check. return Quote{parcel.goods_cents, *shipping};}And the one place that owns the rates:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Owns every rate the shop offers, by name. Orders and quotes only borrow// a rate for the length of a call.// Each rate lives on the heap, owned by a std::unique_ptr inside the map,// and is deleted when the ShippingOptions object is destroyed. Callers get// plain references to the rates and never delete them.class ShippingOptions {public: // Throws std::invalid_argument if `rate` is null or the name is taken. // Both arguments are taken by value and moved into the map: the caller // writes options.add("post", std::make_unique<PostRate>()) and gives up // ownership of the new rate. void add(std::string name, std::unique_ptr<const ShippingRate> rate);
// Throws std::out_of_range for an unknown name. The reference stays // valid as long as this ShippingOptions object exists. [[nodiscard]] const ShippingRate& find(std::string_view name) const;
[[nodiscard]] std::vector<std::string> names() const; // in name order
private: // std::less<> lets find() look up a std::string_view without a copy. // (With the default std::less<std::string>, the map would need a // std::string, so the name would be copied into one first.) A std::map // keeps its keys sorted, which is why names() comes out in name order. std::map<std::string, std::unique_ptr<const ShippingRate>, std::less<>> rates_;};Who owns what
Section titled “Who owns what”Composition makes ownership a design decision, so write it down:
| Object | Owns | Borrows | Lifetime rule |
|---|---|---|---|
ShippingOptions |
every rate, through std::unique_ptr |
nothing | lives as long as the shop offers those options; usually for the whole program |
FreeAbove |
the rate it wraps, through std::unique_ptr |
nothing | the inner rate lives exactly as long as the offer; the offer cannot be copied or moved, so it is held through std::unique_ptr |
Order |
its items, by value | nothing | ordinary value; can be copied and moved |
quote(order, rate) |
nothing | the order and the rate, for one call | returns a std::optional<Quote> by value, which holds no references |
find(name)’s result |
nothing | a rate inside ShippingOptions |
valid as long as that ShippingOptions object exists |
Nothing in the design holds a pointer that someone else owns for longer
than one call. That is a direct result of not storing the chosen rate
inside Order: a stored const ShippingRate* would have to outlive the
order, and nothing in the types would enforce it. So where does the
customer’s choice live during checkout? As the option’s name, a
std::string held by the checkout screen, which calls
options.find(name) each time it needs a price.
Why each choice
Section titled “Why each choice”- Design the interface from all the implementations you have. Looking
at post alone suggests that
cost_centsreturns anint. Collect in store shows that a rate may be unable to ship a parcel at all, so the function returnsstd::optional<int>. An interface designed from the first implementation would not fit the third. - One function,
const. A rate only answers a question, so the function isconst, and options holdconst ShippingRate. Because the rates also have no data that changes, one rate can be shared by any number of quotes, even from several threads. (constalone would not promise that; having nothing mutable does.) Parcel, notOrder, as the parameter. A rate gets only what it needs: weight, value, and destination. It cannot change the basket, and it can be tested without building anOrder. That is the data coupling from cohesion and coupling.finalon the rates. Nobody should derive fromPostRateto make a variant of it. A new tariff is a new class implementingShippingRate, or a composed one.- The offer asks the wrapped rate first.
FreeAbovereturns empty when the wrapped rate cannot ship. An offer makes delivery cheaper; it cannot make it possible. The testfree_above_wraps_any_ratechecks this with collect in store abroad. - The offer cannot be moved.
FreeAboveowns its inner rate through astd::unique_ptr. A moved-fromFreeAbovewould hold a null pointer, and callingcost_centson it would dereference null. Deleting the move operations removes that state entirely; offers are created withstd::make_uniqueand never need to move. - Offers apply abroad too. The old
FreeShippingOrderexisted only at home, by accident of which subclasses were written. In the new design, “free post from 50.00” also applies abroad, as the output shows. If the shop wants home-only offers, that is a real rule, and it belongs in an offer class (or a parameter ofFreeAbove), not in a new class per destination. Check behaviour changes like this with the people who own the rules.
Other ways to vary behaviour in C++
Section titled “Other ways to vary behaviour in C++”A virtual interface is one tool. Choose by how the variation behaves:
| Tool | Good when | Poor when |
|---|---|---|
enum class and switch |
the set of cases is small, fixed, and owned by one team | cases are added often, or combine with each other |
| virtual interface (this page) | cases are added over time, combine, or are chosen at run time; implementations have their own data | there is only ever one implementation |
std::function<std::optional<int>(const Parcel&)> |
the behaviour is one function, with no name, no state anyone inspects, and no other functions | you need several related functions, or want each case to be a named, documented type |
| template parameter | the choice is known at compile time and speed matters | the choice is made at run time (a customer picks it), or you need a list of mixed cases |
std::variant of rate types |
the set is closed, and you want value types with no heap allocation | other teams need to add new cases without editing the variant |
For the shop, the choice is made at run time by a customer, rates are
added over time, and offers wrap other rates. A virtual interface fits
all three. A std::function could too (an offer would capture the
function it wraps). The interface is chosen because each rate is a named,
documented type that can be found in the code and tested by name, and
because there is room for a second function, such as a description to
show at checkout, without changing every caller’s type. The Strategy and Decorator patterns, covered in the patterns
section, are names for exactly these two shapes: an object that can be
swapped (a rate) and an object that wraps another of the same interface
(an offer).
Check: the same basket, every option
Section titled “Check: the same basket, every option”The program prices the same basket with the five old subclasses, then
with one Order at home and one abroad against every option:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Set up the shop's options once. std::make_unique<PostRate>() creates// a PostRate on the heap and returns the std::unique_ptr that owns it;// add() takes over that ownership. The offer is built from two of them:// the inner make_unique creates the PostRate, and FreeAbove takes it.ShippingOptions options;options.add("collect in store", std::make_unique<CollectInStore>());options.add("courier", std::make_unique<CourierRate>());options.add("post", std::make_unique<PostRate>());options.add("post, free from 50.00", std::make_unique<FreeAbove>(5000, std::make_unique<PostRate>()));// The requirement change: free courier from 80.00 is a new combination,// not a new class.options.add("courier, free from 80.00", std::make_unique<FreeAbove>(8000, std::make_unique<CourierRate>()));
// Two orders with the same items, one at home and one abroad. Neither// is told how it will be shipped. (book and lamp are defined above// this snippet: two 18.00 books of 400 g, and a 29.00 lamp of 1500 g.)Order home{false};home.add(book);home.add(lamp);Order abroad{true};abroad.add(book);abroad.add(lamp);
print_options("at home", home, options);print_options("abroad", abroad, options);print_options quotes one order against every option, borrowing each
rate for one call:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Quotes one order against every option. The rate is borrowed for one call.// The order is never copied or changed: the same Order is priced with each// rate in turn.void print_options(const std::string& label, const Order& order, const ShippingOptions& options) { std::cout << "-- after: one order " << label << ", every option --\n"; // names() returns a new vector of names, sorted; the loop reads each one. for (const std::string& name : options.names()) { // A declaration inside the `if`: `price` is the std::optional<Quote> // that quote returns, and the if tests it. A full optional counts as // true, so the first branch runs only when the rate can ship, and // `price->` reaches the Quote inside it. find(name) lends the rate. if (const auto price = quote(order, options.find(name))) { print_line(name, price->shipping_cents, price->total_cents()); } else { std::cout << " " << name << ": not available\n"; } }}-- before: one class per combination -- Order shipping 6.00 total 71.00 ExpressOrder shipping 9.90 total 74.90 InternationalOrder shipping 12.00 total 77.00 InternationalExpressOrder shipping 21.90 total 86.90 FreeShippingOrder shipping 0.00 total 65.00-- after: one order at home, every option -- collect in store shipping 0.00 total 65.00 courier shipping 9.90 total 74.90 courier, free from 80.00 shipping 9.90 total 74.90 post shipping 6.00 total 71.00 post, free from 50.00 shipping 0.00 total 65.00-- after: one order abroad, every option -- collect in store: not available courier shipping 21.90 total 86.90 courier, free from 80.00 shipping 21.90 total 86.90 post shipping 12.00 total 77.00 post, free from 50.00 shipping 0.00 total 65.00The basket is two books (400 g each) and a lamp (1500 g): 65.00 of goods and 2.3 kg. Post at home is 4.50 plus 1.50 for the started kilogram above 2 kg, so 6.00; abroad it is twice that. The new design gives the same prices as the old classes where both exist. It also gives the combinations the old design never had: collect in store, free courier from 80.00 (not reached by 65.00), and free post abroad. Collect in store abroad is reported as not available, instead of a misleading 0.00.
The tests price each rate with a Parcel made up in the test, check that
the offer works with any rate, change the shipping choice on one order
without copying it, and compare the composed rates with all five old
classes, below and above the free-shipping threshold:
VerifiedCompiled 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, 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.
// Each rate is tested with a Parcel made up in the test: no Order needed.// {2000, 0, false} builds a Parcel: 2000 g, goods worth 0, at home.// Comparing the std::optional<int> result with 450 is true only if the// optional holds a value and that value is 450.// 2000 g is exactly the limit (no extra kg); 2001 g starts one extra kg// (+1.50); 3001 g starts two (+3.00); abroad doubles 6.00 to 12.00.LLD_TEST(post_charges_per_started_kilogram_above_two) { const PostRate post; LLD_CHECK(post.cost_cents({2000, 0, false}) == 450); LLD_CHECK(post.cost_cents({2001, 0, false}) == 600); LLD_CHECK(post.cost_cents({3001, 0, false}) == 750); LLD_CHECK(post.cost_cents({2001, 0, true}) == 1200); // abroad: double}
// 10 kg is still the flat 9.90; 1 g more starts a kilogram (+0.80).LLD_TEST(courier_is_flat_up_to_ten_kilograms) { const CourierRate courier; LLD_CHECK(courier.cost_cents({10000, 0, false}) == 990); LLD_CHECK(courier.cost_cents({10001, 0, false}) == 1070); LLD_CHECK(courier.cost_cents({500, 0, true}) == 2190); // abroad: +12.00}
// At home the answer is a real 0; abroad it is an empty optional, which// has_value() reports as false.LLD_TEST(collect_in_store_is_free_at_home_and_unavailable_abroad) { const CollectInStore collect; LLD_CHECK(collect.cost_cents({5000, 0, false}) == 0); LLD_CHECK(!collect.cost_cents({5000, 0, true}).has_value());}
// Composition: one offer class works with every carrier.// The second field of each Parcel is the goods value: 49.99 pays the// courier's 9.90, 50.00 ships free. Wrapping collect in store, even a// threshold of 0 cannot make it ship abroad. A null inner rate is refused// (nullptr converts to an empty std::unique_ptr).LLD_TEST(free_above_wraps_any_rate) { const FreeAbove free_courier{5000, std::make_unique<CourierRate>()}; LLD_CHECK(free_courier.cost_cents({800, 4999, false}) == 990); LLD_CHECK(free_courier.cost_cents({800, 5000, false}) == 0); const FreeAbove free_collect{0, std::make_unique<CollectInStore>()}; LLD_CHECK(!free_collect.cost_cents({800, 9000, true}).has_value()); LLD_CHECK_THROWS(FreeAbove(5000, nullptr), std::invalid_argument);}
// Choosing another way to ship does not copy or rebuild the order.// PostRate{} is a temporary rate that lives until the end of the line,// long enough for quote to use it. `by_post && ...` checks that the quote// exists before reading it with ->. Two books: 3600 cents, 800 g.// The last check: an item with quantity 0 is refused.LLD_TEST(one_order_is_quoted_with_any_rate) { Order order{false}; order.add({"book", 1800, 400, 2}); const auto by_post = quote(order, PostRate{}); const auto by_courier = quote(order, CourierRate{}); LLD_CHECK(by_post && by_post->total_cents() == 3600 + 450); LLD_CHECK(by_courier && by_courier->total_cents() == 3600 + 990); LLD_CHECK_THROWS(order.add({"pen", 100, 10, 0}), std::invalid_argument);}
// find returns a reference to the stored rate, which is used at once. A// second "post", a null rate, and an unknown name are all refused. (void)// says find's result is ignored on purpose; find is [[nodiscard]].LLD_TEST(options_own_rates_and_refuse_bad_names) { ShippingOptions options; options.add("post", std::make_unique<PostRate>()); LLD_CHECK(options.find("post").cost_cents({100, 0, false}) == 450); LLD_CHECK_THROWS(options.add("post", std::make_unique<CourierRate>()), std::invalid_argument); LLD_CHECK_THROWS(options.add("none", nullptr), std::invalid_argument); LLD_CHECK_THROWS((void)options.find("drone"), std::out_of_range);}
// The composed rates charge what the five subclasses charged.// A 2600 g lamp (29.00) goes into each of the five old objects and into// two new orders. Each old class is then compared with the matching// order-and-rate pair. quote(...)-> reads the Quote without checking it is// there; that is safe here because post and courier can always ship.// Then a 55.00 atlas pushes the goods to 84.00, above the 50.00 threshold,// and both designs must agree that post is now free.LLD_TEST(composed_rates_match_the_old_subclasses) { const Item heavy{"lamp", 2900, 2600, 1}; before::Order post; before::ExpressOrder express; before::InternationalOrder post_abroad; before::InternationalExpressOrder express_abroad; before::FreeShippingOrder free_post; post.add(heavy); express.add(heavy); post_abroad.add(heavy); express_abroad.add(heavy); free_post.add(heavy);
Order home{false}; home.add(heavy); Order abroad{true}; abroad.add(heavy); const FreeAbove free_from_50{5000, std::make_unique<PostRate>()};
LLD_CHECK(quote(home, PostRate{})->shipping_cents == post.shipping_cents()); LLD_CHECK(quote(home, CourierRate{})->shipping_cents == express.shipping_cents()); LLD_CHECK(quote(abroad, PostRate{})->shipping_cents == post_abroad.shipping_cents()); LLD_CHECK(quote(abroad, CourierRate{})->shipping_cents == express_abroad.shipping_cents()); LLD_CHECK(quote(home, free_from_50)->shipping_cents == free_post.shipping_cents());
// Above the threshold, both designs ship for free. const Item atlas{"atlas", 5500, 1200, 1}; free_post.add(atlas); home.add(atlas); LLD_CHECK(free_post.shipping_cents() == 0); LLD_CHECK(quote(home, free_from_50)->shipping_cents == free_post.shipping_cents());}Limits of the example: money is an int count of cents and weight an
int count of grams, which a real shop would wrap in types of their own;
the rates’ numbers are constants in the code, where a real shop would load
them from configuration; and ShippingOptions cannot remove or replace an
option, so the references find returns never dangle while it exists.
add refuses negative prices and weights but not huge ones, so a large
enough basket would overflow the int sums in goods_cents and
weight_grams, which is undefined behaviour in C++.
Interfaces with one implementation
Section titled “Interfaces with one implementation”“Program to an interface” is often read as “every class needs an interface in front of it”. That reading produces code like this:
// An interface with one implementation. Every function is pure virtual// (`= 0`), so each one must be written again, with the same signature, in// Order.class IOrder {public: virtual ~IOrder() = default; virtual void add(const Item& item) = 0; virtual int goods_cents() const = 0; // ... every public function of Order, repeated};
class Order final : public IOrder { /* the only implementation */ };It costs more than it looks: every public function is written twice; a
reader who follows a call lands on the interface, not the code; objects
often end up on the heap, held through pointers; and each change
to Order’s functions is made in two places. In return it gives nothing,
because no code ever chooses between two kinds of order.
Before adding an interface, ask:
- Is there a second implementation now, or a concrete, scheduled one? “A second carrier next quarter, contract signed” counts. “We might switch databases one day” does not.
- Does a test need to replace this dependency? Code that reads the clock, the network, the file system, or a random number generator is hard to test unless the test can supply its own. That is a real variation point with two implementations: the real one and the test one. (Sometimes passing the value in, such as the current time, is simpler still.)
- Is this a boundary between teams or libraries? An interface can let two teams work against an agreed contract.
If none apply, use the concrete class. In this design, Order,
ShippingOptions, Parcel, and started_kg_above have no interfaces.
Order is the class most code uses, and it is the one that needs an
interface least. If a second implementation appears later, extracting an
interface is a small change if callers already take the class by
reference (const Order&): declare the abstract class, make the old class
implement it, and change those parameter types. It is harder if code
copies the objects or stores them by value (std::vector<Order>), because
polymorphic objects must then be held through pointers or references, and
copying them would slice. A class used mostly as a value, like Order, is
another reason not to give it an interface early.
A later page in this section, on the cost of unnecessary abstraction, goes further into this trade-off.
When not to
Section titled “When not to”- The cases are few and fixed. Two payment states, three log levels,
or the four suits of a card deck: an
enum classand aswitchare clearer than four classes. - Inheritance models a real “is a” relationship and shares an
interface, not a stash of data. Implementing
ShippingRateis inheritance, and it is the right tool. What composition replaces is inheriting implementation to get variations. - The variation is data. Abroad, colour, size, tax rate: store a value. A class per value is the same mistake as the bad solution.
- Speed-critical inner loops. A virtual call through a pointer usually
costs little, but it can prevent inlining. In a hot loop, a template or
a
std::variantmay be better. Measure before deciding.
Trade-offs
Section titled “Trade-offs”| You gain | You pay |
|---|---|
| one class per carrier or offer, not per combination | more, smaller classes, and a reader must find which ones are composed |
| the choice can change at run time without copying the order | rates live on the heap and are used through references |
| new carriers and offers need no change to existing code | the interface itself is hard to change once many classes implement it |
| each rate is tested alone, with plain values | the program’s actual behaviour depends on how objects are put together, so that setup code needs a test too |
The last row matters. In the composed design, “free post from 50.00” is
not a class you can read; it is a line in the code that builds
ShippingOptions. That setup code is part of the design and deserves
tests and a clear home.
Common mistakes
Section titled “Common mistakes”- A subclass for every variant. If class names start combining words
(
InternationalExpressFreeOrder), the variations are combining, and they should be separate objects. - Making a type out of data.
HomeOrderandAbroadOrderfor abool. - An interface designed from the first implementation. It matches post perfectly and cannot express “not available”. Look at all known cases before writing the interface.
- Fat interfaces. An interface with ten functions that most implementations leave empty or make throw. Split it, or rethink where the variation is.
- Storing a borrowed pointer to save passing it.
Orderholding aconst ShippingRate*creates a lifetime rule that the types cannot enforce. Pass the rate to the call that needs it, or own it. - Interfaces for everything. See the section above. An interface that never has a second implementation is a cost with no return.
When a requirement changes
Section titled “When a requirement changes”Change 1: free courier from 80.00. In the old design, this needs a
new subclass, FreeShippingExpressOrder, and another for abroad, and both
must decide whether to derive from ExpressOrder or FreeShippingOrder
(C++ allows both, through multiple inheritance, which makes things worse).
In the new design, it is already in the example, and it is one line in the
setup code, with no new class:
// A courier rate wrapped in a free-above-80.00 offer, owned by `options`.options.add("courier, free from 80.00", std::make_unique<FreeAbove>(8000, std::make_unique<CourierRate>()));Change 2: a parcel locker. 3.50 flat, home only, up to 5 kg. It is one new class, and it works with every existing offer at once. A sketch (syntax-checked against the example headers, but not part of the compiled example):
// One more implementation of the interface. It cannot ship abroad or over// 5 kg (an empty optional); otherwise it charges a flat 3.50.class LockerRate final : public ShippingRate {public: [[nodiscard]] std::optional<int> cost_cents(const Parcel& parcel) const override { if (parcel.abroad || parcel.weight_grams > 5000) return std::nullopt; return 350; }};
// The existing offer wraps the new rate with no change to FreeAbove. Over// 5 kg the offer, too, reports "not available".options.add("parcel locker", std::make_unique<LockerRate>());options.add("parcel locker, free from 30.00", std::make_unique<FreeAbove>(3000, std::make_unique<LockerRate>()));Order, quote, FreeAbove, the other rates, and all existing tests are
unchanged. In the old design, the locker would need LockerOrder and
FreeShippingLockerOrder at least.
Exercise: Is an interface warranted?
For each case, decide whether to introduce an interface, and say why. If not, say what you would do instead.
- A
PriceFormatterturns cents into"12.50". There is one implementation. The shop sells in one currency and has no plans to change. - A parking meter charges by the minute. Its
ParkingSessionreads the current time from the system clock in three places. The tests cannot check “two hours costs 4.00” without waiting two hours. - Payments go to one card provider. The shop has signed a contract with a second provider, which goes live next quarter. Customers will choose at checkout.
- A small command-line to-do tool saves its list to one JSON file. A
developer suggests a
TodoRepositoryinterface “in case we move to a database”.
Show the explained answer
1. No interface. There is one behaviour and no planned second one,
and the formatter has no dependency that is hard to test. Use a plain
function, std::string format_price(int cents). If a second currency
arrives, the change will show what really varies (perhaps a currency
value passed in, which is data, not a type).
2. Yes, or pass the time in. The clock is a real variation point with
two implementations: the system clock, and a test clock that the test
controls. A small interface, such as
class Clock { public: virtual ~Clock() = default; virtual std::chrono::system_clock::time_point now() const = 0; };,
passed to ParkingSession by reference, makes the class testable.
(system_clock gives the time of day, which a meter needs if its tariff
depends on the hour. To measure only how long a car stayed,
std::chrono::steady_clock is safer, because it never jumps when the
system time is corrected.) A
simpler alternative, if the session only needs the time at a few calls,
is to pass the time as a parameter: int charge_cents(time_point started, time_point ended). Then no interface is needed at all. The
dependency injection page, later in this section, covers both.
3. Yes. There will be two implementations soon, the choice is made at run time by the customer, and the providers are outside systems that tests will want to replace. Design the interface from what both providers’ contracts require (for example, a payment that can be declined or can fail to reach the provider), not only from the first one.
4. No interface yet. There is one storage format and no concrete plan
for another. Keep a concrete class, for example TodoFile, with a narrow
public interface (load, save), so that the rest of the program does
not know about JSON. If a database ever arrives, the narrow class makes it
easy to extract an interface then. The narrow public interface is the
part that matters now; the abstract class can wait.
Summary
Section titled “Summary”- Composition over inheritance: get varying behaviour from parts an object holds or is given, not from subclasses. Implementing an interface is fine; inheriting implementation to make variants is what to avoid.
- Programming to an interface: code that uses a behaviour depends on a
small abstract type, such as
const ShippingRate&. - Find the variation point first. A difference in data is a value, not a type. Things that combine must be separate objects, or the classes multiply.
- Design an interface from all the implementations you know about.
- Write down who owns what. Owning through
std::unique_ptrand borrowing only for the length of a call keeps lifetimes simple. - An interface with one implementation and no test or team reason is
a cost with no return. Small fixed sets of cases are often best as an
enum class.