Incremental design evolution
What you will learn on this page
Section titled “What you will learn on this page”- How to take a design through a series of requirement changes that nobody knew about at the start, one change at a time, each small enough to review.
- A routine for each change: read it against the design; if the design has no place for it, make one first with a refactoring that changes no result; then make the change.
- How to check each step against the version before it, so that the earlier version is the judge of what was meant to stay the same.
- How to protect a public interface that other programs, released on their own schedule, depend on: add with defaults, keep old signatures while callers move, and treat a change of behaviour as a change of interface.
- How to decide between refactoring a part and rewriting it.
The problem
Section titled “The problem”A company runs a car park in a city centre. Its fee calculator is a
small library with one function, parking_fee, which takes a stay
and returns a price in cents. Two programs call it: the software in
the barrier at the exit, and the mobile app, which shows a driver the
price so far. Neither is released with the library. The barrier’s
software is updated a few times a year, by another team; the app is
updated when its users choose to.
The first rules are simple:
- A stay of up to 15 minutes is free.
- Otherwise, every started hour costs 3.00.
- No 24 hours, counted from entry, cost more than 18.00.
Over the next year, three changes arrive, one at a time. Nobody knew about the second when the first was made, or about the third when the second was:
- Change 1: motorcycles pay half, and vans one and a half times.
- Change 2: the daily cap applies to each calendar day, not to each 24 hours from entry.
- Change 3: a second car park opens, at the station, with different prices that depend on the time of day; more are planned.
The aim is a design that takes each change as it comes: no step is a big rewrite, every step can be reviewed and tested on its own, and neither the barrier nor the app has to change unless it wants the new behaviour.
The starting version
Section titled “The starting version”The header is all that the callers see:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Money in whole cents, as a 64-bit whole number: 300 means 3.00.using Cents = std::int64_t;
// A time on the car park's own clock, to the minute. Daylight saving is// not handled: callers give times on a clock that never jumps.// std::chrono::local_time is a point in time on a local clock that is not// tied to any time zone; <std::chrono::minutes> says it counts whole// minutes. Subtracting two Times gives a std::chrono::minutes duration.
using Time = std::chrono::local_time<std::chrono::minutes>;
// One visit: when the car came in and when it left. A plain struct with// public members, so a caller can write Stay{entry, exit}.struct Stay { Time entry; Time exit;};
// The fee for one stay. Throws std::invalid_argument if exit is before entry.Cents parking_fee(const Stay& stay);The time is std::chrono::local_time, a time on the car park’s own
clock, counted in minutes, and the price is a whole number of cents,
so no price here is ever rounded; change 3 adds the first rounding,
and says where. The body:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The prices. An unnamed namespace keeps them private to this file. 15min// and 24h are std::chrono durations, written with the literals switched on// by `using namespace std::chrono_literals;` above.namespace {constexpr auto grace = 15min; // a stay this short is freeconstexpr Cents per_hour = 300; // for each started hourconstexpr Cents day_cap = 1'800; // the most that 24 hours can cost} // namespace
// Works the fee out in one go: whole days at the day cap, plus the started// hours of what is left, at most one day cap.Cents parking_fee(const Stay& stay) { if (stay.exit < stay.entry) { throw std::invalid_argument("exit is before entry"); } // Time minus Time is a duration: how long the stay was, in minutes. const auto stayed = stay.exit - stay.entry; if (stayed <= grace) { return 0; } // A duration divided by a duration is a plain whole number, rounded // down: how many full 24 hours fit in the stay. const auto whole_days = stayed / 24h; // `stayed % 24h` is the part of the stay after the whole days. Adding // 59 minutes before dividing by an hour rounds up, so any started hour // counts: 1 minute gives 1, 60 minutes gives 1, 61 minutes gives 2. const auto started_hours = (stayed % 24h + 59min) / 1h; // Example: noon to noon the next day plus 1 minute is 1,441 minutes: // 1 whole day (18.00), and 1 started hour (3.00), so 21.00 in all. // std::min keeps the last part from costing more than one day. return whole_days * day_cap + std::min(started_hours * per_hour, day_cap);}How this code works: The starting parking_fee, with real stays
- Refuse an impossible stay. An exit before the entry throws
std::invalid_argument. - Free if short.
stayedis the length of the stay in minutes. Up to and including 15 minutes costs nothing. - Split the stay into whole days and the rest.
stayed / 24hcounts the full 24 hours;stayed % 24his what is left over. - Count the started hours of the rest. Adding 59 minutes, then dividing by an hour, rounds up: any part of an hour counts as a whole one.
- Price it. Each whole day costs the cap, 18.00. The rest costs 3.00 per started hour, but never more than one cap.
| stay | minutes | whole_days |
rest | started_hours |
fee |
|---|---|---|---|---|---|
| 16 minutes | 16 | 0 | 16 | 1 | 300 |
| 6 hours 1 minute | 361 | 0 | 361 | 7 | 7 × 300 = 2,100, capped to 1,800 |
| 24 hours 1 minute | 1,441 | 1 | 1 | 1 | 1,800 + 300 = 2,100 |
| 49 hours 15 min | 2,955 | 2 | 75 | 2 | 2 × 1,800 + 600 = 4,200 |
The first three are in the tests of the rules. A stay of exactly 24
hours has a rest of 0, so (0 + 59) / 60 is 0 started hours, and the
fee is one cap, 1,800.
The constants are in an unnamed namespace in the .cpp file, so no
caller can use them. That matters more than it looks: the public
interface is the header, plus what the header promises the function
does. Everything else can change without asking anyone. The more
that is kept out of the header, the more of the next three changes
will be free.
A routine for each change
Section titled “A routine for each change”Each change follows the same four steps:
- Read the change against the design. Which parts does it touch? Does the design already have a place where this kind of thing varies, or would the change have to be spread through code that was not built for it?
- If there is no place for it, make one first, by a refactoring that changes no result, checked against the version before. A widely quoted piece of advice, attributed to Kent Beck, puts it as “make the change easy, then make the easy change”. The refactoring and the change are separate steps, reviewed separately.
- Make the change, with tests of the new rules worked out by hand, since no earlier version knows them.
- Check the interface. Does every existing call still compile? Does every existing caller still get what it got before, unless the change was meant to change that? If a caller has to move, how does it move, and how long can the old way stay?
Every version is kept in the example, in folders named start, v1,
v2-prep, v2, and v3, so that the tests can compare them. In real
work there is one version in version control, and the earlier one is
the commit before. The tests run each version over the same 378 stays:
seven entry times, from midnight to one minute before the next, times
eighteen lengths, from no time at all to a week, times three vehicles.
The values sit on and around every edge in the rules: 15 and 16
minutes, whole hours, six hours, where 3.00 an hour reaches the cap,
24 hours, and midnight.
Change 1: vehicles
Section titled “Change 1: vehicles”“Motorcycles pay half, and vans one and a half times, both per hour and for the daily cap.”
Reading it against the design. The rates are two constants, so
the rule fits inside the function: the rates become a choice by
vehicle. The interface is the problem: parking_fee has no way to
know the vehicle. Three ways to tell it:
- A second parameter,
parking_fee(stay, vehicle). Without a default, every existing call stops compiling, and the barrier and the app would have to be released at the same time as the library, which they are not. With a default,Vehicle vehicle = Vehicle::car, the calls compile again, but each future input would lengthen the list, whenStayalready exists to carry what is known about a stay. - An overload, keeping
parking_fee(stay)for cars. That works, but every future input would need another overload, and code that takes the function’s address,auto f = &parking_fee;, stops compiling once there are two. - A new member of
Stay, with a default.Stayis already a parameter object, so it can grow.
The third is the cheapest that works:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The kinds of vehicle that pay different prices. An enum class: a fixed// list of names, written Vehicle::car, that does not turn into an int.enum class Vehicle { car, motorcycle, van };
struct Stay { Time entry; Time exit; // Added in change 1. Callers written before it, which say Stay{entry, exit}, // still compile and still mean a car, which is all there was. // `= Vehicle::car` is a default member initializer: any Stay built // without a third value gets a car. Aggregate initialization fills // members in the order they are declared, which is why it goes last. Vehicle vehicle = Vehicle::car;};The new member goes at the end. Stay{entry, exit} still compiles,
and the default, a car, is what every stay was before vehicles
existed, so every existing caller still gets the same price. Putting
it anywhere else breaks positional initialization. The following
does not compile, with either compiler, which is the point:
// Does not compile, on purpose: the new member is in the wrong place.struct Stay { Time entry; Vehicle vehicle = Vehicle::car; // added in the middle Time exit;};// Braces fill the members in declaration order: entry, then vehicle,// then exit. So `exit`, a Time, is given to `vehicle`, a Vehicle, and// there is no conversion from one to the other.Stay stay{entry, exit}; // the second value now initializes vehicleGCC reports that it cannot convert Time to Vehicle, and Clang
that there is no viable conversion. The strong types made a silent
mistake into a compile error. If all three members were plain
integers of the same type, the same line would compile, with the exit time in
vehicle; GCC and Clang warn about the member left without a value
only with -Wextra. That is one more reason, from
strong types and API contracts, not to
pass times and kinds as bare numbers.
The body changes only where the rates come from:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Private to this file (unnamed namespace), as before. The grace period is// the same for every vehicle; the rates are not.namespace {constexpr auto grace = 15min;
// The two prices that depend on the vehicle, kept together.struct Rates { Cents per_hour; Cents day_cap;};
// The rates for one kind of vehicle. Each `return {300, 1'800};` builds a// Rates from the braces: per_hour first, then day_cap. Motorcycles pay half// the car prices and vans one and a half times.Rates rates_for(Vehicle vehicle) { switch (vehicle) { case Vehicle::car: return {300, 1'800}; case Vehicle::motorcycle: return {150, 900}; case Vehicle::van: return {450, 2'700}; } // Reached only if `vehicle` holds none of the three names, which a // cast from a stray int could do. Every case above returns, so this // line also tells the compiler that the function never falls off its // end without a value. throw std::invalid_argument("unknown vehicle");}} // namespace
Cents parking_fee(const Stay& stay) { if (stay.exit < stay.entry) { throw std::invalid_argument("exit is before entry"); } const auto stayed = stay.exit - stay.entry; if (stayed <= grace) { return 0; } // The only new line in the body: look up this vehicle's rates once, // then use them where start used its two constants. const Rates rates = rates_for(stay.vehicle); const auto whole_days = stayed / 24h; const auto started_hours = (stayed % 24h + 59min) / 1h; return whole_days * rates.day_cap + std::min(started_hours * rates.per_hour, rates.day_cap);}Checking it. Two kinds of test. The rules for motorcycles and vans
are new, so they are tested with prices worked out by hand: two hours
on a motorcycle is 2 × 1.50 = 3.00. The rules for cars are not new, so
the start version is the judge: over every car stay in the grid, v1
must give exactly what start gave.
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_EQ(actual, expected) records a// failure, printing both values, if they differ. Both come from the site's// small test header, lld_test.hpp.//// grid::cases() is the list of 378 stays (entry, exit, kind of vehicle).// compare(c, now, before, differences) prints the stay and adds one to// `differences` when the two prices are not equal; `differences` is passed// by reference, so compare can count into it. Each test then expects 0.//// Change 1: for every car stay, v1 must charge exactly what start charged.LLD_TEST(adding_vehicles_left_car_prices_alone) { int differences = 0; for (const grid::Case& c : grid::cases()) { // Only cars: start knows nothing else. {c.entry, c.exit} builds a // v1::Stay for the first call and a start::Stay for the second; the // v1 one gets the default vehicle, a car, exactly as an old caller // would. if (c.vehicle == grid::Kind::car) { compare(c, v1::parking_fee({c.entry, c.exit}), start::parking_fee({c.entry, c.exit}), differences); } } LLD_CHECK_EQ(differences, 0);}
// The preparing refactoring for change 2: over every stay and every// vehicle, v2-prep must charge exactly what v1 charged.LLD_TEST(grouping_hours_into_periods_changed_no_price) { int differences = 0; for (const grid::Case& c : grid::cases()) { // Each version has its own Vehicle type, so grid::as<T> converts the // grid's vehicle into version T's (the three names are in the same // order in every version, so a car stays a car). compare(c, v2_prep::parking_fee({c.entry, c.exit, grid::as<v2_prep::Vehicle>(c.vehicle)}), v1::parking_fee({c.entry, c.exit, grid::as<v1::Vehicle>(c.vehicle)}), differences); } LLD_CHECK_EQ(differences, 0);}The second test in that region belongs to change 2, below. A comparison like this is the golden master from the previous page, without the file: since the old version is still there, it is run directly, and a difference names the stay. Once the old version is deleted, its results can be recorded, as on that page.
Text description of the diagram
Two parts, before and after. Before: a Stay box holding entry and exit, with an arrow to parking_fee, which uses two constants, 3.00 per hour and an 18.00 day cap. After: the Stay box holds entry, exit, and vehicle, which defaults to car, with an arrow to parking_fee, which has a dashed arrow labelled “calls” to rates_for(vehicle), giving a car 3.00 and 18.00, a motorcycle 1.50 and 9.00, and a van 4.50 and 27.00. A flow arrow from the Before group to the After group shows the change.
Diagram source (Mermaid)
flowchart TB
subgraph Before
B1["Stay<br/>entry, exit"] --> B2["parking_fee<br/>uses per_hour 3.00, day_cap 18.00"]
end
subgraph After
A1["Stay<br/>entry, exit,<br/>vehicle = car"] --> A2["parking_fee"]
A2 -.->|calls| A3["rates_for(vehicle)<br/>car 3.00 / 18.00<br/>motorcycle 1.50 / 9.00<br/>van 4.50 / 27.00"]
end
Before --> AfterChange 2: a cap for each calendar day
Section titled “Change 2: a cap for each calendar day”“Drivers who park overnight pay one day’s cap for nearly two days. The cap should apply to each calendar day.”
Reading it against the design. The rule needs something the code
does not have. start and v1 work only from the length of the
stay: whole 24-hour periods, then the hours left over. They never ask
what time of day an hour falls in. A calendar day needs exactly that.
One question had to go back to the people who own the prices before
any code was written: an hour that starts at 23:30 ends at 00:30, so
which day does it belong to? Starting hours on the clock, at 23:00 and
00:00, instead of from entry would change the price of many stays,
even daytime ones, since 12:30 to 13:30 would then cover two hours;
splitting the hour would charge 3.00 twice. The answer: hours are
still counted from entry, and an hour belongs to the day on which it
starts. That decision is now part of the interface’s promise, so
it is written in the header’s comment on parking_fee, as well as in
the code next to the rule.
The design has no place for “which day does this hour belong to”, so it gets one first.
The preparing refactoring
Section titled “The preparing refactoring”The new shape bills each started hour in turn, puts it in a period,
and caps each period. Which period an hour belongs to is one small
function, period_of. In this step a period is still 24 hours from
entry, so every price must stay the same:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Which capped period a billed hour belongs to: here, the number of whole// 24-hour periods since entry, as before.std::chrono::days period_of(Time entry, Time hour_start) { return std::chrono::days{(hour_start - entry) / 24h};}} // namespace
Cents parking_fee(const Stay& stay) { if (stay.exit < stay.entry) { throw std::invalid_argument("exit is before entry"); } if (stay.exit - stay.entry <= grace) { return 0; } const Rates rates = rates_for(stay.vehicle); // Bill each started hour in turn, and cap what each period costs. // total: the capped cost of every period already finished. // this_period: the uncapped cost so far of the period being filled. // period: which period that is; the first hour is in period 0. Cents total = 0; Cents this_period = 0; std::chrono::days period = period_of(stay.entry, stay.entry); // `hour` is the start of each billed hour: entry, entry + 1h, and so on, // while it is before the exit. A stay of 61 minutes has two: at entry // and an hour later. So the loop runs once per started hour. for (Time hour = stay.entry; hour < stay.exit; hour += 1h) { // This hour starts a new period: close the old one, capped, and // start counting the new one from zero. if (period_of(stay.entry, hour) != period) { total += std::min(this_period, rates.day_cap); this_period = 0; period = period_of(stay.entry, hour); } this_period += rates.per_hour; // bill this hour to its period } // The last period is still open when the loop ends: cap it and add it. return total + std::min(this_period, rates.day_cap);}How this code works: The loop over billed hours
The loop keeps three variables: total, what the finished periods cost
after capping; this_period, what the current period has cost so far,
before capping; and period, which period that is. period_of
divides the time since entry by 24 hours and rounds down, so hours 0 to
23 of a stay are in period 0, hours 24 to 47 in period 1, and so on.
hourstarts at the entry and moves on one hour at a time while it is still before the exit, so the loop runs once for each started hour.- If
houris in a different period from the one being filled, that period is finished: its cost, capped, is added tototal, and counting starts again from zero for the new period. - The hour’s price is added to the current period.
- After the loop, the last period is still open, so it is capped and added once more.
A car from 12:00 for 30 hours. Hours 0 to 23 after entry are in period 0, and hours 24 to 29 in period 1.
| billed hours | period | this_period at the end |
capped | total after |
|---|---|---|---|---|
| 12:00 … 11:00 (24) | 0 | 24 × 300 = 7,200 | 1,800 | 1,800 |
| 12:00 … 17:00 (6) | 1 | 6 × 300 = 1,800 | 1,800 | 3,600 |
The result, 3,600, is what v1 gives: one whole day at the cap plus six
started hours, 1,800, at most one cap. Only period_of decides where a
period ends, which is why change 2 needs to change only that function.
Nothing in the header changes. The test is the second one in the
region above: over all 378 stays, v2-prep must give exactly what
v1 gave. It passed. To find out what it would catch, scratch copies
of v2-prep were given one mistake at a time:
| Deliberate mistake in the refactoring | Stays that differ, of 378 |
|---|---|
The loop runs while hour <= stay.exit |
63 |
| A finished period is added without its cap | 84 |
| The grace period is dropped | 42 |
Each is the kind of slip a restructuring makes, and each was caught,
with the stays named. The tests of the rules check only the released
versions, so they could not have caught these. Hand-worked tests are
also weaker than they look: had the same three slips been made in
v2 itself, its rule tests would have caught the first two and
missed the dropped grace period. A preparing refactoring is checked
by comparison, not by new tests.
The new shape has a cost. start worked out a price in a few
operations whatever the length of the stay; the loop takes one turn
per billed hour, so a week takes 168 turns and a car left for a year
takes 8,760. For a fee worked out once per stay, that is nothing, and
it buys a place to put the new rule. For a function called millions
of times a second, it might not be, and the closed form could be kept
with the period rule worked into it, at the cost of harder code.
The change itself
Section titled “The change itself”With the place made, the change is a few lines. This is the whole
diff from v2-prep to v2, leaving out the lines that only change
the include, the namespace, and the snippet markers:
// Which capped period a billed hour belongs to: here, the number of whole// 24-hour periods since entry, as before.std::chrono::days period_of(Time entry, Time hour_start) { return std::chrono::days{(hour_start - entry) / 24h};// Change 2: a billed hour belongs to the calendar day on which it starts.std::chrono::days period_of(Time hour_start) { return std::chrono::floor<std::chrono::days>(hour_start).time_since_epoch(); }@@ // period: which period that is; the first hour is in period 0. // period: which calendar day that is, as a count of days since the clock's epoch. Cents total = 0; Cents this_period = 0; std::chrono::days period = period_of(stay.entry, stay.entry); std::chrono::days period = period_of(stay.entry); // `hour` is the start of each billed hour: entry, entry + 1h, and so on, // while it is before the exit. A stay of 61 minutes has two: at entry // and an hour later. So the loop runs once per started hour. for (Time hour = stay.entry; hour < stay.exit; hour += 1h) { // This hour starts a new period: close the old one, capped, and // start counting the new one from zero. if (period_of(stay.entry, hour) != period) { if (period_of(hour) != period) { total += std::min(this_period, rates.day_cap); this_period = 0; period = period_of(stay.entry, hour); period = period_of(hour); }std::chrono::floor<std::chrono::days> rounds a time down to the
midnight before it, so two hours on the same calendar day have the
same period.
Checking it. This change is meant to change prices, so comparing
with v2-prep cannot expect no differences. It can expect them in
one place only: a stay whose billed hours all start on one calendar
day has the same periods either way, so its price must not change.
The test says exactly that:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Change 2 was meant to change some prices, but only of stays whose billed// hours start on more than one calendar day.// So it compares only those stays, and expects v2 to agree with v2-prep on// every one of them. The other stays are left to the hand-worked tests.LLD_TEST(calendar_day_caps_change_only_stays_over_midnight) { using namespace std::chrono; int differences = 0; for (const grid::Case& c : grid::cases()) { // How many hours are billed: the length rounded up to whole hours // (adding 59 minutes before dividing rounds up, as in the fee). const auto started_hours = (c.exit - c.entry + 59min) / 1h; // When the last billed hour starts: entry plus (that count - 1) // hours. A stay of no time bills nothing, so the ?: uses entry itself. const grid::Time last_hour = c.entry + hours{started_hours > 0 ? started_hours - 1 : 0}; // floor<days> rounds a time down to the midnight before it. Same // midnight for the first and the last billed hour: every billed hour // starts on one calendar day, so change 2 must not alter the price. if (floor<days>(last_hour) == floor<days>(c.entry)) { compare(c, v2::parking_fee({c.entry, c.exit, grid::as<v2::Vehicle>(c.vehicle)}), v2_prep::parking_fee({c.entry, c.exit, grid::as<v2_prep::Vehicle>(c.vehicle)}), differences); } } LLD_CHECK_EQ(differences, 0);}The new rule itself is tested with prices worked out by hand, including the stay that motivated it:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Prices worked out by hand from change 2's rule: each billed hour belongs// to the calendar day on which it starts, and each day is capped at 18.00// for a car. at(t) is a time t after midnight on Friday 13 March 2026, so// at(24h + 10h) is 10:00 on Saturday. LLD_CHECK_EQ(actual, expected)// records a failure, with both values, if they differ.LLD_TEST(v2_caps_each_calendar_day) { // 20:00 to 10:00: four hours on the first day, then ten, capped at 18.00. LLD_CHECK_EQ(v2::parking_fee({at(20h), at(24h + 10h)}), 1'200 + 1'800); // The same stay under v1, which caps 24 hours from entry: 14 hours in // one period, capped once. This is the stay that motivated change 2. LLD_CHECK_EQ(v1::parking_fee({at(20h), at(24h + 10h)}), 1'800); // 10:00 to 10:00: fourteen hours on the first day and ten on the // second, each day capped. LLD_CHECK_EQ(v2::parking_fee({at(10h), at(24h + 10h)}), 1'800 + 1'800); // An hour that starts before midnight is billed to the day it starts in. // 23:30 to 00:30 is one hour, starting on Friday: 3.00. LLD_CHECK_EQ(v2::parking_fee({at(23h + 30min), at(24h + 30min)}), 300); // 23:30 to 01:00 is two started hours, 23:30 on Friday and 00:30 on // Saturday: 3.00 on each day. LLD_CHECK_EQ(v2::parking_fee({at(23h + 30min), at(25h)}), 600); // Six hours in one day reach the cap exactly: 6 x 3.00 = 18.00. LLD_CHECK_EQ(v2::parking_fee({at(10h), at(16h)}), 1'800);}The scope test guards only the stays whose price must not change.
Where prices may change, these hand-worked prices are the only judge,
so they cover each part of the new rule: a first day under the cap, a
first day over it, and the 23:30 hour. The 10:00 to 10:00 check was
added after a review. Without it, a scratch copy of v2 that added the
first day without its cap passed every rule test and the scope test;
only change 3’s comparison, written later, would have caught it.
A car from 20:00 to 10:00 the next day used to cost 18.00: fourteen hours, inside one 24-hour period, capped. Now it costs 30.00: four hours on the first day, 12.00, and ten on the second, capped at 18.00.
What changed, measured. A scratch program ran v2-prep and v2
over the grid. Of the 378 stays, 99 cost more and none cost less, by
between 1.50 and 27.00; the 27.00 is a van, whose cap is 27.00, gaining
a whole extra day’s cap. Of the 150 stays whose billed hours start on
more than one day, 51 kept their price, because both ways of counting
gave the same caps. Those numbers are for this grid, not a proof
about every stay. They are what the owners of the prices were shown
before the release: which kinds of stay go up, by how much, and that
nothing goes down.
Text description of the diagram
Two parts, before and after. Before: parking_fee works out the price as the number of whole 24-hour periods times the cap, plus the leftover hours, capped. After: parking_fee bills each started hour and caps each period, with a dashed arrow labelled “calls” to period_of, which in v2-prep takes the entry and the hour’s start and returns the number of 24-hour periods since entry, and in v2 takes only the hour’s start and in v2 returns the calendar day on which the hour starts. A flow arrow from the Before group to the After group shows the change.
Diagram source (Mermaid)
flowchart TB
subgraph Before
B1["parking_fee<br/>whole 24 h periods × cap<br/>+ capped leftover hours"]
end
subgraph After
A1["parking_fee<br/>bills each started hour,<br/>caps each period"] -.->|calls| A2["period_of(...)<br/>v2-prep: 24 h periods from entry<br/>v2: the calendar day it starts on"]
end
Before --> AfterChange 3: a second car park
Section titled “Change 3: a second car park”“We are opening a car park at the station. It charges by the half hour: 1.50 from 07:00 to 19:00 and 0.50 otherwise, with a cap of 12.00 a calendar day and a grace period of 10 minutes. Vehicles pay the same percentages as in the city centre. Two more car parks are planned for next year, with prices still to be decided.”
Reading it against the design. Every price in v2 is a constant
in code: the grace period, the hour, and a table of rates by vehicle.
A second car park in the same style would be a second copy of the
function, and two more planned car parks would make four. What
varies between car parks is data, so the prices should become data:
a value that says what one car park charges, passed to one function.
The loop of change 2 nearly fits. It bills steps of an hour at one price and caps each calendar day. The station needs steps of half an hour, at a price that depends on the time of day the step starts. Both are small generalizations of the same loop.
Refactor or rewrite?
Section titled “Refactor or rewrite?”At this point the code had been changed twice, and the team asked whether it was time to throw it away and write a general pricing engine. The questions that decided it:
| Question | Here |
|---|---|
| Does the current structure still fit the new rules? | Yes: billed steps, capped per day, are still the model. |
| Is the knowledge in the code written down anywhere else? | Only in the tests: grace, started hours, the 23:30 decision. |
| Is there a judge for what must stay the same? | Yes: v2, and the grid of 378 stays. |
| Is the part small, with a narrow interface? | Yes: one function and one struct. |
| Are the future rules known well enough to design an engine for? | No: two car parks have no prices yet. |
Those answers say to refactor. A general engine designed now would have to guess what the next two car parks will charge, which is speculative generality, the code smell that YAGNI warns against: it would cost more now and, when the real prices arrived, probably be wrong in some other way. What is known is that prices vary by car park and by time of day, so that, and only that, becomes data.
The same table points the other way when the answers change. Rewrite a part, rather than refactor it, when the model itself has changed so much that every rule fights the old structure; when the part is small and its interface narrow, so the rewrite can be finished; and when there is a judge for what must stay, so the rewrite can be checked. Even then, build the new part behind the same interface, run it on the same inputs as the old one and compare, which is often called a parallel run, and switch callers over only when they agree. Replacing a larger system piece by piece in this way, with old and new living side by side until the old is gone, is widely called the strangler fig approach. A rewrite without a judge loses the rules nobody wrote down; here, those would be that a 15-minute stay is free but a 16-minute one costs a whole hour, and that the 23:30 hour belongs to the day it starts on.
Prices as data
Section titled “Prices as data”The new type, Tariff, holds one car park’s prices. It is a class,
not a struct, because a tariff has rules of its own, which the
constructor checks:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A price per step for a car, from a time of day until the next band starts.// The station's peak band, for example, is {7h, 150}: from 07:00, 1.50 a// step. A band has no end time; the next band's `from` is its end.struct Band { std::chrono::minutes from; // after midnight Cents per_step;};
// One car park's prices. A stay no longer than the grace period is free.// Otherwise each started step is billed at the band in which it starts,// and no calendar day costs more than the day cap; a step belongs to the// day on which it starts. Other vehicles pay a// fixed percentage of the car price, the same in every car park.//// A class, not a struct, because its members are private and only the// constructor can set them, after checking them: so every Tariff that exists// is valid, and price_at can rely on that.class Tariff {public: // Throws std::invalid_argument unless the grace period and the prices // are not negative, the step is longer than zero, and the bands start // at midnight and then in increasing order, all before the next midnight. // `bands` is taken by value: the parameter is a vector of its own (a copy // of the caller's, or built straight from a brace list), and it is then // moved into the Tariff, so no second copy is made. Tariff(std::chrono::minutes grace, std::chrono::minutes step, std::vector<Band> bands, Cents day_cap);
std::chrono::minutes grace() const { return grace_; } std::chrono::minutes step() const { return step_; } Cents day_cap() const { return day_cap_; } // The car price of a step that starts at this time: the price of the // band whose start is the latest one at or before that time of day. Cents price_at(Time step_start) const;
private: std::chrono::minutes grace_; std::chrono::minutes step_; std::vector<Band> bands_; Cents day_cap_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The constructor first stores the four values (the list after the colon),// then checks them. If a check fails it throws, and no Tariff is made at// all, so code that holds a Tariff never meets an invalid one.// std::move(bands) hands the parameter's elements to bands_ without copying.Tariff::Tariff(std::chrono::minutes grace, std::chrono::minutes step, std::vector<Band> bands, Cents day_cap) : grace_(grace), step_(step), bands_(std::move(bands)), day_cap_(day_cap) { if (grace_ < 0min || step_ <= 0min || day_cap_ < 0) { throw std::invalid_argument("negative grace or cap, or a step that is not positive"); } // Checked first, so bands_.front() is only read when there is a band. if (bands_.empty() || bands_.front().from != 0min) { throw std::invalid_argument("the first band must start at midnight"); } // Each band: a price that is not negative, a start before the next // midnight, and (from the second band on) a start later than the one // before. `i > 0 &&` comes first so bands_[i - 1] is never read for i 0. for (std::size_t i = 0; i < bands_.size(); ++i) { if (bands_[i].per_step < 0 || bands_[i].from >= 24h || (i > 0 && bands_[i].from <= bands_[i - 1].from)) { throw std::invalid_argument("bands must be in increasing order within one day"); } }}
// Finds the band a step starts in, and returns that band's car price.Cents Tariff::price_at(Time step_start) const { // floor<days> rounds the time down to the midnight before it, so the // difference is the time of day, in minutes after midnight. const auto time_of_day = step_start - std::chrono::floor<std::chrono::days>(step_start); // The last band that starts at or before this time; the first starts at // midnight, so there always is one. // std::upper_bound searches the sorted bands (binary search) for the // first band that starts AFTER time_of_day. The lambda is the test it // uses: "does this time come before this band's start?". `after` is an // iterator to that band, or bands_.end() if no band starts later. const auto after = std::upper_bound( bands_.begin(), bands_.end(), time_of_day, [](std::chrono::minutes time, const Band& band) { return time < band.from; }); // std::prev steps back one band: the last one starting at or before the // time. It is safe because `after` is never the first band: that one // starts at midnight, which is never after time_of_day. // Example, station at 18:59: the first band after it starts at 19:00, so // the one before, from 07:00, gives 150. At 19:29 no band starts later, // `after` is end(), and the one before it, from 19:00, gives 50. return std::prev(after)->per_step;}The constructor is the only way to make a Tariff, so every tariff
that exists has bands that start at midnight and increase, and a step
longer than zero. Those are the
invariants that
price_at relies on: since the first band starts at midnight, the
band before after always exists, and std::prev is safe. A tariff
loaded from a file later would go through the same check.
The loop is the one from change 2, with the step and the price taken from the tariff, and the vehicle table replaced by a percentage. Taking a percentage is the first place a price could be rounded; it rounds down to a whole cent, and the comment says that every price in both tariffs divides exactly:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
namespace {// What each vehicle pays, as a percentage of the car price.Cents percent_of_car_price(Vehicle vehicle) { switch (vehicle) { case Vehicle::car: return 100; case Vehicle::motorcycle: return 50; case Vehicle::van: return 150; } throw std::invalid_argument("unknown vehicle");}} // namespace
// The fee for one stay at one car park. The loop is change 2's, with the// step, the prices, and the grace period read from the tariff: bill each// started step at the price of the band it starts in, add the steps of// each calendar day, cap each day, and add up the days.Cents parking_fee(const Stay& stay, const Tariff& tariff) { if (stay.exit < stay.entry) { throw std::invalid_argument("exit is before entry"); } if (stay.exit - stay.entry <= tariff.grace()) { return 0; } // Rounds down to a whole cent; every price in both tariffs divides exactly. const Cents percent = percent_of_car_price(stay.vehicle); // Multiply first, then divide, so nothing is lost before the division. // A van at the city centre: 1,800 * 150 / 100 is 2,700. const Cents day_cap = tariff.day_cap() * percent / 100; Cents total = 0; // the capped cost of every finished day Cents today = 0; // the uncapped cost so far of the day being filled // The midnight that starts the entry's calendar day. auto day = std::chrono::floor<std::chrono::days>(stay.entry); // `step` is the start of each billed step, while it is before the exit. for (Time step = stay.entry; step < stay.exit; step += tariff.step()) { // A step on a new calendar day: close the old day, capped, and // start the new one from zero. if (std::chrono::floor<std::chrono::days>(step) != day) { total += std::min(today, day_cap); today = 0; day = std::chrono::floor<std::chrono::days>(step); } // This step's car price, scaled for the vehicle, rounded down. today += tariff.price_at(step) * percent / 100; } // The last day is still open: cap it and add it. return total + std::min(today, day_cap);}How this code works: A night at the station, step by step
A car at the station from 22:00 on Friday to 08:00 on Saturday. The
station’s tariff has 10 minutes’ grace, half-hour steps, and bands
starting at 00:00 (50), 07:00 (150), and 19:00 (50), with a cap of
1,200 a day. A car pays 100 percent, so day_cap is 1,200.
- The stay is 10 hours, well past the grace period, so it is billed.
dayis Friday’s midnight. Steps start at 22:00, 22:30, 23:00, and 23:30. For each,price_atfinds the last band starting at or before that time of day, the one from 19:00, so each step costs 50.todayreaches 200.- The step at 00:00 is on Saturday:
floor<days>of it is a different midnight. Friday is closed:totalbecomesmin(200, 1,200), 200, andtodaygoes back to 0. - Saturday’s steps from 00:00 to 06:30 are 14 steps in the band from
midnight, 50 each, so 700. The steps at 07:00 and 07:30 are in the
band from 07:00, 150 each.
todayis 1,000. - The next step would start at 08:00, which is not before the exit, so
the loop ends. The result is
200 + min(1,000, 1,200), 1,200, the value the station test expects.
For a motorcycle, percent is 50: every step costs half, and so does
the day cap, 600. Each step is scaled and rounded down on its own, which
is exact here because every price in both tariffs is a multiple of 2.
The two tariffs, and the old signature:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each tariff is a `static` local: built the first time the function is// called (safely, even if two threads call it at once), and then kept// until the program ends. That is why returning a reference to it is safe:// the object stays alive while the program runs, after the call returns.const Tariff& city_centre() { // The old prices as data. The arguments: 15 minutes' grace, one-hour // steps, one band {from midnight, 300 a step}, and the day cap. // 3.00 for each started hour at any time of day, at most 18.00 a day. static const Tariff tariff(15min, 1h, {{0min, 300}}, 1'800); return tariff;}
const Tariff& station() { // The arguments: 10 minutes' grace, 30-minute steps, three bands as // {start, price a step}, and the day cap. // Half hours: 1.50 from 07:00 to 19:00 and 0.50 otherwise, at most 12.00 a day. static const Tariff tariff(10min, 30min, {{0min, 50}, {7h, 150}, {19h, 50}}, 1'200); return tariff;}
// The deprecated old signature just forwards to the new one with the// city centre tariff, so old callers keep getting the old prices.Cents parking_fee(const Stay& stay) { return parking_fee(stay, city_centre());}Each tariff is a function-local static, made on first use and kept
until the program exits, so the references that city_centre and
station return stay valid for every caller until static objects are
destroyed at exit. Since C++11, that first use is also safe when two
threads make it at once: one builds the tariff and the other waits.
The interface
Section titled “The interface”Callers now have to say which car park:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The prices of the two car parks. Each object lives until the program ends.// They return a const reference: every caller shares the one object, can// read it but not change it, and has nothing to free.const Tariff& city_centre();const Tariff& station();
// The fee for one stay. Throws std::invalid_argument if exit is before entry.Cents parking_fee(const Stay& stay, const Tariff& tariff);
// The signature from before change 3, for callers not yet moved. It still// works, and means the city centre. [[deprecated("...")]] makes the// compiler warn at every call, quoting the message, so callers find out// what to change; a build that treats warnings as errors stops instead.[[deprecated("say which car park: parking_fee(stay, v3::city_centre())")]]Cents parking_fee(const Stay& stay);The old signature stays and means what it always meant, the city
centre, so the barrier and the app keep working, unless they take the
address of parking_fee, which now has to say which overload. It is marked
[[deprecated]], so that every caller that still uses it gets a
warning naming the replacement. The warning is a choice with a cost:
a caller that builds with warnings as errors, as this site’s examples
do, stops building. Both compilers, given a call of the old function
with -Werror, refuse it with an error that quotes the attribute’s
message, “say which car park: parking_fee(stay,
v3::city_centre())”. Tell the callers’ owners before releasing a
deprecation, give them a date by which the old signature goes, and
remove it only when the last caller has moved. A caller who wants
to see the warning without failing the build can add
-Wno-error=deprecated-declarations, which both compilers accept.
Until then the old signature is part of the interface, so it has a test, and that test silences the warning that every other caller sees:
// push saves the current warning settings; the next line turns off the// "deprecated" warning; pop restores the saved settings. So the warning is// off for this one call only, and on again for everything after it.#pragma GCC diagnostic push#pragma GCC diagnostic ignored "-Wdeprecated-declarations" const v3::Cents old_way = v3::parking_fee(stay);#pragma GCC diagnostic popThat excerpt is from the example’s comparison tests, which compile with both compilers; Clang accepts the GCC form of the pragma.
Checking it. Two judges, one for each half of the change. The
city centre’s prices must not change at all, so v3 with the city
centre tariff is compared with v2 over all 378 stays, and must
agree on every one. The station’s prices are new, so they are
checked by hand, including the edges between bands:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The station tariff, by hand: 10 minutes free, then half-hour steps at// 0.50, or 1.50 from 07:00 to 19:00, at most 12.00 a day for a car.LLD_TEST(the_station_bills_half_hours_at_the_band_where_each_starts) { // A reference to the one station tariff object; nothing is copied. const v3::Tariff& station = v3::station(); // 10 minutes is within the grace period; 11 minutes is one step at // 12:00, a peak price. LLD_CHECK_EQ(v3::parking_fee({at(12h), at(12h + 10min)}, station), 0); LLD_CHECK_EQ(v3::parking_fee({at(12h), at(12h + 11min)}, station), 150); // 06:30 off peak, then 07:00 and 07:30 at the peak price. LLD_CHECK_EQ(v3::parking_fee({at(6h + 30min), at(8h)}, station), 50 + 150 + 150); // The same stay on a motorcycle: half of each step's price. LLD_CHECK_EQ(v3::parking_fee({at(6h + 30min), at(8h), v3::Vehicle::motorcycle}, station), 25 + 75 + 75); // 18:59 is still in the peak; 19:29 is not. A step is priced by the // band it starts in, even when most of it falls in the next band. LLD_CHECK_EQ(v3::parking_fee({at(18h + 59min), at(19h + 30min)}, station), 150 + 50); // 18:00 to 21:00: two peak steps (18:00, 18:30), then four off peak. LLD_CHECK_EQ(v3::parking_fee({at(18h), at(21h)}, station), 2 * 150 + 4 * 50); // Twenty peak half hours, capped: 20 x 1.50 is 30.00, but a day costs at // most 12.00. LLD_CHECK_EQ(v3::parking_fee({at(8h), at(18h)}, station), 1'200); // 22:00 to 08:00: four half hours on the first day; fourteen off peak // and two at the peak on the second. LLD_CHECK_EQ(v3::parking_fee({at(22h), at(24h + 8h)}, station), 4 * 50 + 14 * 50 + 2 * 150);}The comparison was given a deliberate mistake too: with the day cap not scaled by the vehicle’s percentage, 114 of the 378 stays differ, all of them motorcycles and vans, since a car pays 100 percent. A test of car prices alone would have missed it.
The demo prices four stays with every version. Each line changes only where a change meant it to:
Car, 12:00 to 14:00 start (no vehicles) 6.00 v1 6.00 v2 6.00 v3, city centre 6.00 v3, station 6.00Motorcycle, 12:00 to 14:00 start (no vehicles) 6.00 v1 3.00 v2 3.00 v3, city centre 3.00 v3, station 3.00Car, 20:00 to 10:00 next day start (no vehicles) 18.00 v1 18.00 v2 30.00 v3, city centre 30.00 v3, station 16.00Car, 06:30 to 08:00 start (no vehicles) 6.00 v1 6.00 v2 6.00 v3, city centre 6.00 v3, station 3.50Text description of the diagram
Two parts, before and after. Before: parking_fee(stay) has dashed arrows labelled “calls” to rates_for(vehicle), which holds the prices as constants in code, and to period_of(hour). After: a deprecated parking_fee(stay) has a dashed “calls” arrow to parking_fee(stay, tariff), which has a dashed “reads” arrow to Tariff, holding the grace period, the step, the bands, and the day cap, checked when it is made, and a dashed “calls” arrow to percent_of_car_price(vehicle). city_centre() and station() each have a dashed “returns” arrow to Tariff. A flow arrow from the Before group to the After group shows the change.
Diagram source (Mermaid)
flowchart TB
subgraph Before
B1["parking_fee(stay)"] -.->|calls| B2["rates_for(vehicle)<br/>constants in code"]
B1 -.->|calls| B3["period_of(hour)"]
end
subgraph After
A0["parking_fee(stay)<br/>deprecated"] -.->|calls| A1["parking_fee(stay, tariff)"]
A1 -.->|reads| A2["Tariff<br/>grace, step, bands, day cap<br/>checked when made"]
A3["city_centre()"] -.->|returns| A2
A4["station()"] -.->|returns| A2
A1 -.->|calls| A5["percent_of_car_price(vehicle)"]
end
Before --> AfterWhen this fits, and when it does not
Section titled “When this fits, and when it does not”Evolving a design one change at a time fits when the changes are not
known in advance, which is most of the time. Each step is small, and
the code at every step is only as general as the requirements so far.
The Tariff of change 3 would have been a guess on the first day:
nobody then knew about vehicles, calendar days, or time-of-day bands,
and an engine designed for imagined car parks would have been built
around the wrong things.
It does not mean never designing ahead:
- When a change is known, design for it. If the station had been in the plan from the start, prices as data would have been the right first design, not a later refactoring.
- When an interface is expensive to change, think harder about it
first. The
Stayparameter object is what made change 1 cheap. A public function of two bare times would have needed an overload for every new input. Interfaces that others compile against are worth more thought up front than the code behind them. - When the changes have stopped, a later tidy-up can be worth it. Evolution leaves traces, such as a deprecated signature or a type named for its history, and once nothing more is coming, those can go.
Common mistakes
Section titled “Common mistakes”- Making the change and the refactoring in one step. If the prices then differ, nobody can tell whether the new rule or the restructuring caused it. Change 2 was two steps, each with its own check.
- Adding a parameter where a member would do. Without a default, every caller stops compiling, and callers released on their own schedule cannot all move at once. With one, the calls compile, but the list grows with every input.
- A default that changes the old meaning. A new member’s default must give existing callers what they got before. If no value does, the change is not compatible, and the callers have to be told.
- Treating “it compiles” as “it is compatible”. Change 2 kept every signature and changed what overnight stays cost. A promise in a comment or a document is part of the interface.
- Deleting a deprecated signature on a schedule nobody agreed to. Removing it breaks every caller that has not moved. Find the callers first.
- Rewriting because the code looks old. The question is whether the structure still fits the rules, not how many times it has been changed. A rewrite loses every rule that is only in the code.
- Building the general version early. A pricing engine on the first day would have been designed for guesses, and paid for long before it was needed.
When the requirements change
Section titled “When the requirements change”The next request: the city centre car park is fitting charging points
for electric cars, at 0.40 per kilowatt hour. It is tempting to add
kwh to Stay and a charging rate to Tariff. Read it against the
design first. Charging is not parking: it is metered by the charger,
not the clock, it may be billed by another company, and a car can
park without charging. It belongs in its own function, with its own
input, and the receipt shows two lines. parking_fee and its callers
do not change at all. Not every change belongs in the abstraction
that is already there, and the cheapest change is the one that does
not touch the protected interface. The parking lot case study, later
in the site, designs a whole car park, including its fees.
Exercise
Section titled “Exercise”Exercise: Plan the next change
The city centre’s shops want to offer their customers free parking.
A shop can stamp a driver’s ticket, and a stamped stay at the city
centre has its first two hours free. The barrier’s software will
learn to read a stamp in its next release, in about four months; the
app will never see stamps. Starting from v3:
- Read the change against the design. What does it touch, and does
Tariffhave a place for it? - What questions must go back to the people who own the prices before any code is written?
- How does a caller say that a stay was stamped, without breaking the barrier’s current release or the app?
- Is a preparing refactoring needed? What would it be?
- Which tests show that nothing else changed, and which test the new rule?
Show the explained answer
-
It touches the stay and the tariff. Whether a stay was stamped is a fact about the stay, like the vehicle. How much a stamp is worth is a fact about the car park: the station has no shops, and the two planned car parks may differ. So
Stayneeds a new member, andTariffneeds the free time for a stamp, zero for the station.Tariffhas no place for a discount yet, and the loop has none either. -
The edges of the rule. Do the two free hours come off before the day cap or after it? Is a stamped stay of two hours and five minutes charged for the five minutes, for the whole third hour, or given its own grace period? Can a ticket carry two stamps? Do motorcycles get the same two hours? Each answer changes the code, and each is the owners’ decision, not the programmer’s; like the 23:30 hour in change 2, it should be written next to the rule.
-
A member at the end of
Stay, with a default that means “not stamped”. That is what every stay before this change was, so the current barrier and the app get the prices they get now. This was compiled with both compilers:struct Stay {Time entry;Time exit;Vehicle vehicle = Vehicle::car;// Added for shop stamps. Callers written before it still mean a stay// without a stamp.bool stamped = false;};// Designated initializers name each member set; `vehicle` is not named,// so it keeps its default, a car. The names must be in declaration order.Stay stamped_car(Time entry, Time exit) { return Stay{.entry = entry, .exit = exit, .stamped = true}; }The designated initializer, from C++20, lets a caller set
stampedwithout restating the vehicle.Tariffgains a member for the free time with a stamp, set by its constructor and checked there: not negative. That constructor is public, so the new parameter goes last, with a default of no free time, or every place that builds aTariffstops compiling. -
Probably a small one. The loop bills every step from entry. If the answer to question 2 is “the first two hours are not billed”, the change is to start billing two hours later for a stamped stay, which fits the loop without a refactoring. If the answer is “two hours’ worth of money comes off the total, after the cap”, the change is one subtraction at the end, also without one. If free time can come from several sources later, such as stamps and season tickets, a refactoring that works out “the time to bill” in one function first would make each later source a small change; but with one source and no others planned, that would be designing for a guess.
-
The comparison tests, extended. Over all 378 stays, unstamped, the new version must agree with
v3for both tariffs, since nothing changed for them; that covers the station too, now thatv3is the judge for it. Stamped stays at the station must also agree withv3, since its free time is zero. The new rule gets hand-worked tests at its edges: a stamped stay of exactly two hours, of two hours and one minute, one that reaches the day cap, and one over midnight, each with the answers from question 2.
Summary
Section titled “Summary”- Requirements arrive one at a time, and a design can follow them in small steps, each reviewed and tested on its own, if it keeps what callers can see small.
- For each change: read it against the design; if there is no place for it, make one with a refactoring that changes no result; then make the change, as a separate step.
- The previous version is the judge of what was meant to stay the same: compare the two over a grid of inputs. A change meant to change results can still be checked, by saying where it may and may not change them.
- New rules have no judge, so they are tested with numbers worked out by hand.
- Protect a public interface: add members with a default that keeps the old meaning, at the end; keep an old signature, deprecated, until its last caller has moved; and treat a change of behaviour as a change of interface, told to callers before release.
- Refactor while the structure fits. Rewrite a part only when the model has changed, the part is small, and there is a judge for what must stay; even then, run the old and the new side by side first.
- Design ahead for what is known, not for what is guessed.