The Open/Closed Principle
What you will learn on this page
Section titled “What you will learn on this page”- What the Open/Closed Principle (OCP) says, and what “closed” does and does not mean.
- How to find the likely variation: the kind of change that keeps arriving.
- How to tell a change in data (new numbers) from a change in behaviour (a new calculation), and why they need different extension mechanisms.
- How to choose between a table of data, a virtual interface,
std::function, a template, and a plainswitch. - Why an extension point nobody uses is a cost, not a safety net.
The problem
Section titled “The problem”A small online shop started out selling to one region, north, and now sells to south as well. At checkout it must show the sales tax on the basket.
- FR-1 Each product has a category: food, books, clothing, or general goods. Each region taxes each category at its own rate.
- FR-2 Tax is worked out per line (price times quantity), rounded to the nearest cent, half a cent rounding up, and then added up.
- FR-3 An unknown region is an error, never “no tax”.
The shop is growing. This is the tax code’s change log so far this year, with one request still to come. The “before” design on this page is the code as it stood in April, just before east arrived:
| When | Request | Kind of change |
|---|---|---|
| January | Start selling in south | new region, new numbers |
| March | North raises its general rate from 18 % to 20 % | changed numbers |
| May | Start selling in east: clothing under 100.00 an item is tax-free | new region, new rule |
| planned | Start selling in west | new region, new numbers |
The principle
Section titled “The principle”The Open/Closed Principle says a module should be open for extension and closed for modification. In plain words:
When a likely kind of change arrives, you should be able to make it by adding code or data, without editing code that already works and is already tested.
OCP is the “O” in SOLID.
| It does not mean | It does mean |
|---|---|
| “Never edit a class once written” | For the changes you expect, adding beats editing |
| “Make everything extensible” | Choose one or two directions of change, from evidence, and make those cheap |
| “Always use inheritance” | Extension can be new data, a new class, a new function object, or a template argument |
| “The design is closed against every change” | It is closed against some changes; others will still need edits, and that is fine |
Why bother? Editing working code has a cost beyond typing: the change can break the cases that worked, so they must be re-reviewed and retested. Adding a new piece next to the old ones keeps that risk small: the old pieces are not touched, and their tests still mean what they meant.
Step 1: find the change that keeps coming
Section titled “Step 1: find the change that keeps coming”OCP starts with evidence, not with interfaces. Read the change log above and sort the requests:
- New regions arrived twice (south, east), a third is planned (west), and the business plans more. This is the likely variation.
- Changed rates arrived once. They are numbers, not code.
- New categories never arrived. Adding one would touch everything, but nobody has asked.
- A new kind of rule arrived once (east’s tax-free clothing). It came with a new region.
So the design should make “add a region” cheap, whether that region needs only new numbers or a new rule. It does not need to make “add a category” cheap yet.
Bad, good, great: adding a region
Section titled “Bad, good, great: adding a region”Before, every region lived in one namespace:
enum class Region
every region, known everywhere
Values
northsouth
namespace before
all regions' rules in one place
Functions
std::string_view region_name(Region region);long long tax_cents(const std::vector<Line>& basket, Region region);a switch per line
After, the facts, the numbers, the rules, and the calculator are separate:
struct Line
one basket line: facts only
Data members
std::string item;Category category;long long unit_price_cents;int quantity;
struct Rates
numbers only: one rate per category, in basis points
Data members
int food_bp;int books_bp;int clothing_bp;int general_bp;
interface (abstract class) TaxRule
how one region taxes one line
Member functions
virtual ~TaxRule() = default;virtual long long tax_cents(const Line& line) const = 0;TaxRule(const TaxRule&) = default;protected, as is operator=: no slicing through TaxRule&
class RateRule final
implements TaxRule; the common case
Data members
Rates rates_;
Member functions
explicit RateRule(Rates rates);throws if a rate is outside 0..10000long long tax_cents(const Line& line) const override;
class ExemptBelowRule final
implements TaxRule; east's calculation
Data members
Rates rates_;Category category_;the category that can be exemptlong long exempt_below_cents_;unit prices below this pay no tax
Member functions
ExemptBelowRule(Rates rates, Category category, long long exempt_below_cents);throws on bad rates or a negative thresholdlong long tax_cents(const Line& line) const override;
class TaxCalculator
closed against new regions
Data members
std::map<std::string, std::unique_ptr<const TaxRule>, std::less<>> rules_;owns one rule per region
Member functions
void add_region(std::string region, std::unique_ptr<const TaxRule> rule);throws on an empty name, null, or a duplicatelong long tax_cents(std::string_view region, const std::vector<Line>& basket) const;throws std::out_of_range if unknown
Text description of the diagram
TaxCalculator, which maps region names to rules, has a solid arrow labelled “owns 1 per region” to the TaxRule interface. RateRule and ExemptBelowRule each have a thick arrow labelled “implements” to TaxRule, and a dashed “uses” arrow to Rates, which holds only numbers. TaxRule has a dashed arrow labelled “reads” to Line, which holds only facts. The main function has dashed arrows labelled “creates and adds” to RateRule and to ExemptBelowRule, and a dashed “uses” arrow to TaxCalculator. No arrow points from TaxCalculator to a concrete rule.
Diagram source (Mermaid)
flowchart TB
TC["TaxCalculator<br/>region name to rule"] -->|owns 1 per region| TR["TaxRule<br/>interface"]
RR["RateRule"] ==>|implements| TR
EB["ExemptBelowRule"] ==>|implements| TR
RR -.->|uses| RT["Rates<br/>numbers"]
EB -.->|uses| RT
TR -.->|reads| LN["Line<br/>facts"]
MN["main()<br/>wiring"] -.->|creates and adds| RR
MN -.->|creates and adds| EB
MN -.->|uses| TCThe new design
Section titled “The new design”The facts and the arithmetic. A Line is a plain struct: it has no
rules, so it needs no invariants of its own beyond what amount_cents
checks. Rates are stored in basis points (hundredths of a percent:
2000 is 20 %), so every rate is a whole number and no floating point is
needed.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One line of a basket: a product, its category, a unit price, a quantity.// A plain struct of facts with no rules of its own. Money is a whole// number of cents in a `long long`, so there is no floating-point// rounding error.struct Line { std::string item; Category category; long long unit_price_cents; int quantity;};
// The line's amount before tax: unit price times quantity. Throws// std::invalid_argument for a negative price or a quantity below 1.long long amount_cents(const Line& line);
// Tax on `amount` at `basis_points` (1 basis point = 0.01 %, so 2000 is// 20 %), rounded half up to a whole cent. Assumes amount * 10000 fits in// a long long (amounts below about 9 * 10^14 cents).// How: it computes (amount * basis_points + 5000) / 10000. Dividing by// 10000 turns basis points into a fraction, and adding 5000 (half of// 10000) first makes integer division round to the nearest cent instead// of always down. Example: 3333 cents at 2000 is 6666000 + 5000 =// 6671000, and 6671000 / 10000 is 667 (the exact tax is 666.6 cents).// Every rule uses this one function, so rounding lives in one place.long long tax_at(long long amount, int basis_points);The extension point. TaxRule is the one place built to be extended.
It is small on purpose: one question, “what is the tax on this line?”. Its
copy operations are protected, so code cannot assign one rule to another
through a TaxRule& (which would copy only the TaxRule part), while each
concrete rule can still be copied whole.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// How one region taxes one line. New regions whose rules differ in// *behaviour* add a new class; they do not edit this one or the others.// It is an interface: `= 0` (pure virtual) means TaxRule has no answer of// its own, and every concrete rule must supply one with `override`.// Callers hold a `const TaxRule&` and call tax_cents; the version that// runs is the real rule's.class TaxRule {public: // Virtual, so destroying a rule through a TaxRule pointer (as the // calculator's unique_ptr does) runs the concrete rule's destructor. virtual ~TaxRule() = default; // The tax in cents on one line. `const`: asking never changes the // rule. A rule may throw for a bad line (they all call amount_cents). virtual long long tax_cents(const Line& line) const = 0;
protected: // Protected: only derived classes construct or copy the TaxRule part, // so nobody can copy "just the TaxRule part" of a concrete rule. TaxRule() = default; TaxRule(const TaxRule&) = default; TaxRule& operator=(const TaxRule&) = default;};The common case, as data. Most regions are one RateRule with their
own Rates. The struct uses named fields, so the wiring reads
.clothing_bp = 2000 rather than a row of bare numbers.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One rate per category, in basis points (2000 = 20 %). Regions whose// rules differ only in *numbers* need only a new Rates value.struct Rates { int food_bp; int books_bp; int clothing_bp; int general_bp;};
// Throws std::invalid_argument unless every rate is in 0..10000// (0 % to 100 %).void check_rates(const Rates& rates);// Picks the one field of `rates` that belongs to `category`, e.g.// rates.books_bp for Category::books. Shared by every rule, so the// mapping from category to rate is written only once.int rate_for(const Rates& rates, Category category);
// The common case: tax is the category's rate times the line amount.// `final`: nothing derives from it. Extension goes through TaxRule.class RateRule final : public TaxRule {public: // Keeps a copy of `rates` and checks it, so a RateRule with a bad // rate never exists: throws std::invalid_argument for a rate outside // 0..10000. explicit RateRule(Rates rates); // Throws std::invalid_argument (from amount_cents) for a bad line. long long tax_cents(const Line& line) const override;
private: Rates rates_; // a copy, owned by value; never changed after the check};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One line: amount_cents(line) checks the line and gives price x quantity,// rate_for picks this category's rate, and tax_at applies it with the// shared rounding. Example (north): a 33.33 lamp at 2000 is 667 cents.long long RateRule::tax_cents(const Line& line) const { return tax_at(amount_cents(line), rate_for(rates_, line.category));}A different calculation, as a class. East’s rule is not “different
numbers”; it is an extra condition. It gets its own class. It reuses the
shared helpers amount_cents, tax_at, and rate_for, so the rounding
rule still lives in one place.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A different calculation, so a new class: lines of one category whose// unit price is below a threshold pay no tax; all other lines use the// rates as RateRule does.// Example from main.cpp: category clothing, threshold 10000 cents// (100.00), so a 15.00 t-shirt pays nothing and a 120.00 coat pays 8 %.class ExemptBelowRule final : public TaxRule {public: // Throws std::invalid_argument for a rate outside 0..10000 or a // negative threshold. ExemptBelowRule(Rates rates, Category category, long long exempt_below_cents); // Throws std::invalid_argument (from amount_cents) for a bad line, // even one that would have been exempt. long long tax_cents(const Line& line) const override;
private: Rates rates_; // the rates for every line not exempt Category category_; // the one category that can be exempt long long exempt_below_cents_; // unit prices strictly below this are exempt};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
long long ExemptBelowRule::tax_cents(const Line& line) const { // Computed before the exemption test on purpose: a line with a bad // quantity or price throws here, instead of slipping through as 0. const long long amount = amount_cents(line); // validates the line first // The exemption needs both: the right category AND a unit price (the // price of one item, not the whole line) strictly below the threshold. // `<`, not `<=`: an item at exactly the threshold is taxed. if (line.category == category_ && line.unit_price_cents < exempt_below_cents_) { return 0; } // Not exempt: the same calculation as RateRule. return tax_at(amount, rate_for(rates_, line.category));}The closed part. TaxCalculator maps a region name to the rule it
owns. Region names are strings, not an enum, so a new region does not edit
a type that the whole program includes. The map’s std::less<> lets
find take a std::string_view without building a std::string.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Totals a basket's tax for a region. Closed against new regions: adding// one is a call to add_region, made where the program is put together.// The calculator never names a concrete rule; it only knows TaxRule.class TaxCalculator {public: // Registers `rule` under the name `region`, and takes ownership of it. // std::unique_ptr is a pointer that owns what it points to and deletes // it when it goes away; there is only ever one owner, so the caller // must hand it over (a temporary from std::make_unique, or std::move). // `const TaxRule`: once added, the rule can only be read. // Throws std::invalid_argument for an empty name, a null rule, or a // region that is already registered; the calculator is then unchanged. void add_region(std::string region, std::unique_ptr<const TaxRule> rule);
// The total tax in cents on every line of `basket`, using the rule // registered for `region`. Throws std::out_of_range for a region that // was never added, so "no rule" never quietly means "no tax". Throws // std::invalid_argument for a bad line. long long tax_cents(std::string_view region, const std::vector<Line>& basket) const;
private: // Region name -> the rule the calculator owns for it. std::map keeps // the names sorted and finds one in O(log n). The third argument, // std::less<>, lets find() compare a std::string_view with the stored // std::string keys directly, without first building a std::string. std::map<std::string, std::unique_ptr<const TaxRule>, std::less<>> rules_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
long long TaxCalculator::tax_cents(std::string_view region, const std::vector<Line>& basket) const { // find returns an iterator: a position in the map. If the name is not // there, it returns end(), the position "one past the last entry". const auto found = rules_.find(region); if (found == rules_.end()) { // std::string{region} makes a string from the string_view so it // can be joined to the message with +. throw std::out_of_range{"no tax rule for region: " + std::string{region}}; } // found->second is the map entry's value, the unique_ptr; `*` gives // the rule it points to. A reference, not a copy: the map still owns // the rule, and `rule` is only a name for it during this call. const TaxRule& rule = *found->second; long long total = 0; for (const Line& line : basket) { // A virtual call: RateRule's or ExemptBelowRule's tax_cents runs, // whichever this region was given. This loop never changes when a // new kind of rule is added. total += rule.tax_cents(line); } return total;}How this code works: TaxCalculator::tax_cents
- Find the region’s rule.
rules_.find(region)looks the name up in the map. It returns an iterator, a position in the map. If the name is not there, the position isrules_.end(), which means “not found”. - No rule is an error, not zero tax. For an unknown name the function
throws
std::out_of_rangestraight away, so a typo such as"nrth"can never produce a basket with no tax. - Borrow the rule. Each map entry is a pair:
firstis the name andsecondis thestd::unique_ptrthat owns the rule.*found->secondfollows that pointer to the rule itself, andconst TaxRule& rulegives it a short name. Nothing is copied or moved: the map still owns the rule, and the reference is used only while this call runs. - Add up the lines. For each line,
rule.tax_cents(line)is a virtual call. For"north"it runsRateRule::tax_cents, for"east"it runsExemptBelowRule::tax_cents. The loop is the same for both, and stays the same when a new kind of rule is added. That is the “closed” part. - Return the total, in cents.
A worked example: "east", with the basket from main.cpp
(ExemptBelowRule, clothing exempt below 100.00, otherwise 8 %):
| Line | Amount (cents) | What the rule does | Tax (cents) | total |
|---|---|---|---|---|
| bread × 2 | 500 | food at 0 % | 0 | 0 |
| novel | 1200 | books at 0 % | 0 | 0 |
| t-shirt × 2 | 3000 | clothing, 1500 an item, below 10000: 0 | 0 | 0 |
| coat | 12000 | clothing, 12000 an item, not below: 8 % | 960 | 960 |
| lamp | 3333 | general, (3333 × 800 + 5000) / 10000 | 267 | 1227 |
The result, 1227, is the “east 1227” line in the output below.
Who owns what. In main.cpp (next), std::make_unique creates each
rule and hands back the only owning pointer. add_region takes it by
value and moves it into the map. From then on the calculator owns every
rule, and they are all deleted when the calculator is destroyed.
Where extension happens. Regions are added in one place, where the program is put together (the composition root):
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The composition root: the one place that names concrete rules.// std::make_unique<RateRule>(...) creates a RateRule on the heap and// returns the std::unique_ptr that owns it; add_region takes that// ownership. (A unique_ptr<RateRule> converts to the parameter type,// unique_ptr<const TaxRule>, because a RateRule is a TaxRule.)// `Rates{.food_bp = 0, ...}` uses designated initializers (C++20): each// field is set by name, in the order the struct declares them.TaxCalculator calculator;calculator.add_region("north", std::make_unique<RateRule>(Rates{ .food_bp = 0, .books_bp = 0, .clothing_bp = 2000, .general_bp = 2000}));calculator.add_region("south", std::make_unique<RateRule>(Rates{ .food_bp = 500, .books_bp = 500, .clothing_bp = 1000, .general_bp = 1000}));
// Added later. No existing class was edited for either region.calculator.add_region("east", std::make_unique<ExemptBelowRule>( Rates{.food_bp = 0, .books_bp = 0, .clothing_bp = 800, .general_bp = 800}, Category::clothing, 10000)); // clothing under 100.00 an item: no taxcalculator.add_region("west", std::make_unique<RateRule>(Rates{ .food_bp = 0, .books_bp = 700, .clothing_bp = 700, .general_bp = 700}));Why each choice
Section titled “Why each choice”| Choice | Why | What it costs |
|---|---|---|
Rates is a struct of numbers, not a class per region |
Regions that differ only in numbers should not need code | A Rates value cannot express a new kind of rule; that is what TaxRule is for |
TaxRule takes one Line |
Every rule so far is per line; a small interface is easy to implement and to test | A rule that needs the whole basket, or the date, does not fit (see below) |
The calculator owns rules as unique_ptr<const TaxRule> |
One owner, clear lifetime; const because a rule never changes after it is added |
A heap allocation per region, made once at start-up |
| Region names are strings | Adding a region edits no type | A typo is a run-time error (std::out_of_range), not a compile error |
| An unknown region throws | FR-3: “no rule” must never quietly mean “no tax” | Callers must handle the exception, or check the name first |
final on the concrete rules |
Nobody needs to derive from them; extension goes through TaxRule |
They cannot be derived from for reuse; wrap them instead (see the exercise) |
Choosing an extension mechanism
Section titled “Choosing an extension mechanism”“Open for extension” does not say how. C++ gives you several ways, and the right one depends on what varies and when it is known.
| Mechanism | Fits when | Watch out for |
|---|---|---|
| Data (a struct, a table, a config file) | The variants differ only in numbers or names | Flags creeping into the data to switch behaviour on and off (the “good” design above) |
Virtual interface (TaxRule) |
The variants differ in behaviour, are chosen at run time, and may hold their own data | One small interface per variation point; heap ownership; a fixed signature (see the requirement changes below) |
std::function |
The behaviour is one function with little or no state, chosen at run time | No name to show in an outline; harder to give it several operations or to test what it holds |
| Template or concept | The variant is known at compile time and speed matters | Every user is compiled with it; errors are harder to read; a new variant means rebuilding the users |
enum and switch |
The set of variants is small and stable, and you want the compiler to check every case | Every new variant edits every switch; this is the “before” design |
The tax calculator uses two of these: data for the many regions that need only numbers, and a virtual interface for the few that need a new calculation. That mix is common. The virtual-interface row, a family of interchangeable calculations behind one interface, is the Strategy pattern, covered in the patterns section.
A switch is not an OCP failure in itself. A switch over Category
inside rate_for is fine: categories have never changed, and if one is
added, the compiler’s -Wswitch warning lists every switch to update.
OCP is about the direction of change you expect.
The program taxes the same five-line basket (two loaves of bread at 2.50, a novel at 12.00, two t-shirts at 15.00, a coat at 120.00, and a lamp at 33.33) with the old design, then with the new one:
before: north 3667 south 1918after: north 3667 south 1918 east 1227 west 1367North and south give the same totals in both designs, and east and west were added without editing any class. Work through east by hand:
| Line | Amount | East’s rule | Tax |
|---|---|---|---|
| bread × 2 | 5.00 | food at 0 % | 0.00 |
| novel | 12.00 | books at 0 % | 0.00 |
| t-shirt × 2 | 30.00 | clothing, 15.00 an item, under 100.00: exempt | 0.00 |
| coat | 120.00 | clothing, 120.00 an item, not exempt: 8 % | 9.60 |
| lamp | 33.33 | general at 8 %: 2.6664, rounded to the nearest cent | 2.67 |
| Total | 12.27 |
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. basket(), north, south,// east, and two_regions() are helpers defined above this snippet: the// same five-line basket and rates as main.cpp, and a calculator with// north and south added.
// The refactoring changed no answer: for both old regions, the new// calculator and the old switch give the same tax on the same basket.LLD_TEST(the_new_design_matches_the_old_one) { const TaxCalculator calculator = two_regions(); LLD_CHECK(calculator.tax_cents("north", basket()) == before::tax_cents(basket(), before::Region::north)); LLD_CHECK(calculator.tax_cents("south", basket()) == before::tax_cents(basket(), before::Region::south));}
// The OCP test itself: record north's answer, add a region, and check// that north's answer did not move. 1227 cents is east's total: 960 on// the coat plus 267 on the lamp (the t-shirts are exempt).LLD_TEST(adding_a_region_leaves_the_others_alone) { TaxCalculator calculator = two_regions(); const long long north_before = calculator.tax_cents("north", basket()); calculator.add_region("east", std::make_unique<ExemptBelowRule>(east, Category::clothing, 10000)); LLD_CHECK(calculator.tax_cents("north", basket()) == north_before); LLD_CHECK(calculator.tax_cents("east", basket()) == 1227);}
// The edge of the exemption: 99.99 is below 100.00 and pays 0; exactly// 100.00 is not below, so it pays 8 % (800 cents). A cheap mug is// general, not clothing, so it is taxed: 500 at 8 % is 40 cents.LLD_TEST(the_exemption_is_strictly_below_the_threshold) { const ExemptBelowRule rule{east, Category::clothing, 10000}; LLD_CHECK(rule.tax_cents({"scarf", Category::clothing, 9999, 1}) == 0); LLD_CHECK(rule.tax_cents({"jacket", Category::clothing, 10000, 1}) == 800); // Only the named category is exempt. LLD_CHECK(rule.tax_cents({"mug", Category::general, 500, 1}) == 40);}
// Rounding at 10 % (south's general rate): 5 cents gives 0.5 cents of// tax, which rounds up to 1; 4 cents gives 0.4, which rounds down to 0.// In tax_at: (5 * 1000 + 5000) / 10000 = 1, (4 * 1000 + 5000) / 10000 = 0.LLD_TEST(tax_is_rounded_half_up_per_line) { const RateRule rule{south}; LLD_CHECK(rule.tax_cents({"pen", Category::general, 5, 1}) == 1); // 0.5 cents LLD_CHECK(rule.tax_cents({"clip", Category::general, 4, 1}) == 0); // 0.4 cents}
// Each kind of bad input throws instead of being taxed as zero: an unknown// region, a region added twice, a null rule, a negative rate, and a line// with quantity 0.LLD_TEST(bad_input_is_refused) { TaxCalculator calculator = two_regions(); LLD_CHECK_THROWS(calculator.tax_cents("nowhere", basket()), std::out_of_range); LLD_CHECK_THROWS(calculator.add_region("north", std::make_unique<RateRule>(north)), std::invalid_argument); LLD_CHECK_THROWS(calculator.add_region("west", nullptr), std::invalid_argument); LLD_CHECK_THROWS( RateRule(Rates{.food_bp = -1, .books_bp = 0, .clothing_bp = 0, .general_bp = 0}), std::invalid_argument); const RateRule rule{north}; LLD_CHECK_THROWS(rule.tax_cents({"ghost", Category::food, 100, 0}), std::invalid_argument);}The first test checks the new design against the old one. The second is the OCP test itself: it records north’s result, adds a new region, and checks that north’s result did not change. The rest check the exemption’s edge (strictly below the threshold, and only for its category), the rounding of half a cent, and that bad input is refused rather than taxed as zero.
Limits of the example
Section titled “Limits of the example”- Money is
long longcents and tax is rounded per line, half up. Real tax law says how to round (per line or per basket) and the two can differ by a cent; a real program would also use a money type. tax_atassumesamount * 10000fits in along long, which holds for any basket below about 9 × 1014 cents, andamount_centsdoes not checkprice * quantityfor overflow either. Real money code checks both.- Rules are registered once at start-up and never removed. The calculator is not safe to modify while another thread reads it.
- A region has one rule. A region that needs two special rules at once needs a class that combines them (see the exercise).
What this design is not closed against
Section titled “What this design is not closed against”Every design is closed against some changes and open to edits for others. Be honest about which is which:
| Change | Closed? | What you would edit |
|---|---|---|
| A new region with its own rates | Yes | Nothing; add one add_region call |
| A new region with a new per-line rule | Yes | Nothing; add a class and one add_region call |
| A rate changes | Yes | One number in the wiring (or a config file) |
| A new category, such as medicine | No | Category, Rates, check_rates, rate_for, and every region’s Rates value |
| A rule that needs the whole basket (“tax capped at 50.00 an order”) | No | TaxRule’s signature, or TaxCalculator, and so every rule |
| A rule that depends on the date | No | TaxRule would need the date, or a rule would need a clock (see the exercise) |
The new category deserves a warning. If you add int medicine_bp; to
Rates, a region written with named fields that does not mention it gets
0, a legal rate, so check_rates cannot catch it. GCC 11 warns
about a missing field in a designated initializer
(-Wmissing-field-initializers, part of -Wextra; with -Werror, as in
this site’s examples, the build fails); Clang 14 says nothing. Do not rely on the warning: a test per region that pins one
line of each category catches it on any compiler.
The cost of premature extension points
Section titled “The cost of premature extension points”Imagine the same shop on day one, with one region and no change log. A developer who has read about OCP writes:
interface (abstract class) TaxRule
one implementation
Member functions
virtual long long tax_cents(const Line& line) const = 0;
interface (abstract class) TaxRuleFactory
one implementation
Member functions
virtual std::unique_ptr<TaxRule> make(std::string_view region) const = 0;
interface (abstract class) RateSource
one implementation, which returns constants
Member functions
virtual Rates rates_for(std::string_view region) const = 0;
interface (abstract class) RoundingPolicy
one implementation
Member functions
virtual long long round(long long amount, int basis_points) const = 0;
Each of these is reasonable on its own, and each costs something:
- a reader must follow four indirections to learn “north taxes clothing at 20 %”;
- every interface has exactly one implementation, so nothing is gained yet;
- guesses about the future are usually wrong in the details. Here, the
real new rule (east’s exemption) needed only the first of the four,
and only once there was a second implementation; it needed no factory,
rate source, or rounding policy. And the thing that might come next (a
basket-level cap) does not fit a per-line
TaxRuleat all.
The simple switch was the right day-one design. The time to open it up
was May, when the second kind of change (a new rule, not new numbers)
actually arrived. Refactoring then, with tests pinning north and south, is
cheap: the first test on this page is exactly that safety net.
When not to apply it
Section titled “When not to apply it”- One or two variants, and no history of change. A
switchis clearer. - The variants are closed by nature. The days of the week, the four
suits of playing cards, the states of a TCP connection. A
switchthat the compiler checks is safer than an open set. - Throwaway or short-lived code. A one-off migration script will not get a second region.
- When adding is not cheaper than editing. If every “extension” also needs changes to the core, the extension point is in the wrong place. Move it, or remove it.
Trade-offs
Section titled “Trade-offs”| You gain | You pay |
|---|---|
| New regions without touching tested code | More types and files than one switch |
| Each rule tested on its own, with small inputs | Behaviour is chosen at run time, so a reader follows the wiring to see what runs |
| Regions as data can come from configuration, without a rebuild | A typo in a region name is found at run time, not compile time |
| The extension point names the variation (“a region’s tax rule”) | It fixes a signature; a change that does not fit it costs more than it would have before |
Common mistakes
Section titled “Common mistakes”- Opening everything. An interface for every class, “just in case”. Each one is a guess and a cost; see the outline above.
- A class per data variant.
NorthTax,SouthTax,WestTax, each with the same code and different numbers. That is data pretending to be behaviour. - Flags in the data. The opposite mistake: a data struct that grows
boolfields andifs for each new kind of rule. When the data starts switching behaviour, behaviour wants its own class. - Treating OCP as a law. Editing code is normal. OCP is about making the frequent change cheap, not about forbidding edits.
- A silent default. A
default: return 0;or a missing map entry that means “no tax” turns a forgotten region into a wrong answer instead of an error. Here an unknown region throws.
When a requirement changes
Section titled “When a requirement changes”South drops its book rate to 0 %. One number in the wiring changes:
.books_bp = 0. No class changes, and the tests of each rule class still
pass. Tests that pin south’s total change, because south’s answer really
did change; the test that compares south against the old design would
fail and should be retired, together with the old design it compares
against.
A new region, isles, charges at least 0.10 on every taxed line. A new
calculation, so a new class that implements TaxRule (one version is in
the exercise’s answer) and one add_region call. Nothing existing changes.
Finance asks for “tax is capped at 50.00 per order”. This is the
change the design is not closed against: TaxRule sees one line at a
time, and a cap needs the whole basket. You must edit something. The
smallest honest edit is in TaxCalculator, if the cap applies to every
region: cap the total after the loop. If only some regions have caps, the
extension point itself is wrong, and TaxRule should change to see the
basket, for example tax_cents(const std::vector<Line>& basket), with
RateRule and ExemptBelowRule summing per line as before. That edit
touches every rule once. After it, basket-level rules are closed too.
Make that change when the request arrives, not before.
Exercise
Section titled “Exercise”Exercise: Choose an extension mechanism for a new rule
The tax calculator on this page is in production. Three requests arrive. For each one, say whether it is a change in data or in behaviour, which mechanism you would use, and which existing classes, if any, you would edit.
- West joins: food 0 %, everything else 7 %.
- Isles joins: rates of 0 % for food and 5 % for everything else, and every taxed line pays at least 0.10, however cheap the item.
- South announces a tax-free weekend for clothing on two dates next month. The rest of the year, south’s rules are unchanged.
Show the explained answer
1. Data. West needs only numbers: a new Rates value and one
add_region call with a RateRule. No class is edited. (It is already in
main.cpp: west’s total is 13.67.)
2. Behaviour. A minimum is a different calculation, so it is a new
class that implements TaxRule. No existing class is edited:
// Exercise answer: a minimum tax on every taxed line. A new class that// implements TaxRule; nothing that already exists is edited.class MinimumPerLineRule final : public TaxRule {public: // Keeps copies of the rates and the minimum, then checks both, so a // rule with bad settings never exists. MinimumPerLineRule(Rates rates, long long minimum_cents) : rates_{rates}, minimum_cents_{minimum_cents} { check_rates(rates_); if (minimum_cents_ < 0) throw std::invalid_argument{"minimum must not be negative"}; } long long tax_cents(const Line& line) const override { const int rate = rate_for(rates_, line.category); const long long amount = amount_cents(line); // validates the line first if (rate == 0) return 0; // untaxed categories stay untaxed const long long tax = tax_at(amount, rate); // `?:` picks the larger: the minimum if the tax is below it, // otherwise the tax itself. return tax < minimum_cents_ ? minimum_cents_ : tax; }
private: Rates rates_; long long minimum_cents_;};With a 0.10 minimum and 5 %, a 0.50 pen pays 0.10 instead of 0.03, bread still pays nothing, and a 120.00 coat pays 6.00. Note the decision hidden in “taxed”: a 0 % category stays at 0, which is what the request says. There is another: a free item (price 0) in a taxed category pays 0.10. Ask before assuming either.
3. Behaviour that needs something TaxRule does not have: the date.
There are two reasonable answers, and the choice is the point:
- Extend, with a wrapping rule. A new class
ExemptOnDatesowns south’s normal rule, holds the two dates and aconst Clock&(as in dependency injection), and returns 0 for clothing on those dates, otherwise asks the rule it wraps. No existing class is edited, and the wrapping shape is the one you met in composition and interfaces. The cost: a tax rule now reads the clock, so the same basket can be taxed differently depending on when you ask, and the date a sale was made is not the date it is re-calculated for a refund. - Modify once, on purpose. Change
TaxRuleto receive the sale’s date, for exampletax_cents(const Line& line, std::chrono::year_month_day sold_on)(a sketch, not compiled). Every rule changes once, and the date becomes an explicit fact of the sale.
If this is the first date-based rule and the dates are fixed, the wrapper is fine. If finance says “we will have these every quarter”, dates are a new likely variation, and passing the sale’s date is the better design.
Summary
Section titled “Summary”- OCP: for the changes you expect, extend by adding code or data, instead of editing code that works.
- Start from evidence: the change log, the business plan, the second request of the same kind. Not from guesses.
- Separate data changes (new numbers: use a table or struct) from behaviour changes (a new calculation: use a new class behind an interface, or a function object).
- Keep the extension point small: one question, one signature.
- Every design is closed against some changes only. Say which, and accept edits for the rest.
- An extension point with one implementation and no history is a cost.
A
switchthe compiler checks is often the right first design.