An engine is well designed if extending it is mostly additive: new behavior arrives as new code, and the compiler and the tests point at the few places that must change. This lesson tries two extensions against that standard. A new policy rule should need no change to the engine at all. A new event type should make the compiler list every place that must handle it.
Extension 1: a per-item limit
Suppose a warehouse caps every item at 200 units, well below the engine's built-in 1000. That is a policy, so it belongs in a Rule:
class PerItemLimit final : public Rule {
public:
explicit PerItemLimit(int maximum) : maximum_(maximum) {} // Require 0 <= maximum <= 1000.
bool accepts(const Inventory& proposed, const Event&) const override {
for (const auto& [id, item] : proposed) {
if (item.quantity > maximum_) { return false; }
}
return true;
}
private:
int maximum_;
};The engine needs no edit: engine.add_rule(std::make_unique<PerItemLimit>(200)); installs it, and apply already calls every rule after every event. The rule obeys the contract in the header. It is const, it reads proposed only during the call, it keeps no pointer into the staged inventory that is about to be swapped or discarded, and it prints nothing. It also ignores the event; checking the whole proposed state is simpler and cannot miss an item.
Test it with a batch that passes ordinary validation but breaks the policy, such as creating an item with 150 and adjusting it by +60. The ordinary 0..1000 range accepts 210, so only the new rule can reject it, at index 1. Also test exactly 200, which must pass, so an accidental >= is caught.
Extension 2: a new event type
Adding struct Delete { int id; }; is more work, and the design makes the compiler find most of it. Add the struct and append it to the Event variant. Then compile. std::visit(ApplyVisitor{staged}, ...) and std::visit(ExportVisitor{}, ...) both fail, because neither visitor can accept a Delete. There is no catch-all overload to hide them. That is the payoff of Day 1's decision to name every overload.
The compiler cannot find the rest, so keep a checklist:
- The parser: a new keyword and its field count.
- The canonical format:
delete|id, plus exact-string and round-trip tests. - The brief and the README: what deleting a missing item does, and whether a deleted ID can be created again in the same batch.
- The tests: a late failure after a delete must restore the item, and a mutant that skips the erase must be killed.
Predict and run
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> quantities{3,7,5};
std::cout << std::all_of(quantities.begin(),quantities.end(),[](int n) { return n <= 7; }) << "\n";
return 0;
}Check your prediction
1Every quantity is at most 7, so all_of is true. Change one quantity to 8 and it becomes false: a single counterexample rejects the policy. Notice what kind of failure that is. 8 is a well-formed, in-range quantity; only the configured policy forbids it. The engine reports it as rule_rejected, distinct from invalid, so a caller can tell "your request was nonsense" from "your request was refused by policy". And all_of over an empty range is true, so an empty inventory satisfies every per-item limit.
Practice
Your turn
Using using Inventory = std::map<int,int>; and a Rule with virtual bool accepts(const Inventory& proposed) const = 0;, write PerItemLimit. Then write const char* try_adjust(Inventory& live, const std::vector<std::pair<int,int>>& changes, const std::vector<std::unique_ptr<Rule>>& rules) that stages, enforces 0..1000 itself, checks every rule after every change, and swaps on success, returning "ok", "invalid" or "rule_rejected". With item 1 at 150 and a limit of 200, print:
+60: rule_rejected, item 1 has 150
+50: ok, item 1 has 200
+60 then -60: rule_rejected, item 1 has 200
+800 without the rule: ok, item 1 has 1000The last line uses an empty rule list.
#include <iostream>
#include <map>
#include <memory>
#include <utility>
#include <vector>
using Inventory = std::map<int,int>;
class Rule {
public:
virtual ~Rule() = default;
virtual bool accepts(const Inventory& proposed) const = 0;
};
int main() {
Inventory live{{1, 150}};
// Write PerItemLimit and try_adjust, then run the four batches.
return 0;
}Hint 1: the idea
The engine-level range check and the policy are separate checks with separate errors. The policy runs after each change, on the staged copy.
Hint 2: a first step
Write try_adjust first and call it with an empty rule list: copy live, apply each change to the copy, return "invalid" if a quantity leaves 0..1000, and swap at the end. Check it on its own before any rule exists: +60 on item 1 at 150 should print ok, item 1 has 210, and +900 on a fresh 150 should print invalid, item 1 has 150. Then write PerItemLimit with a constructor that stores the maximum and an accepts that returns true, add the rule check after every change, and work out which item must make accepts return false.
Show one solution
#include <iostream>
#include <map>
#include <memory>
#include <utility>
#include <vector>
using Inventory = std::map<int,int>;
class Rule {
public:
virtual ~Rule() = default;
virtual bool accepts(const Inventory& proposed) const = 0;
};
class PerItemLimit final : public Rule {
public:
explicit PerItemLimit(int maximum) : maximum_(maximum) {}
bool accepts(const Inventory& proposed) const override {
for (const auto& [id, quantity] : proposed) {
if (quantity > maximum_) { return false; }
}
return true;
}
private:
int maximum_;
};
const char* try_adjust(Inventory& live, const std::vector<std::pair<int,int>>& changes,
const std::vector<std::unique_ptr<Rule>>& rules) {
Inventory staged = live;
for (const auto& [id, delta] : changes) {
auto found = staged.find(id);
if (found == staged.end() || delta < -1000 || delta > 1000) { return "invalid"; }
const int next = found->second + delta;
if (next < 0 || next > 1000) { return "invalid"; }
found->second = next;
for (const auto& rule : rules) {
if (!rule->accepts(staged)) { return "rule_rejected"; }
}
}
live.swap(staged);
return "ok";
}
int main() {
Inventory live{{1, 150}};
std::vector<std::unique_ptr<Rule>> rules;
rules.push_back(std::make_unique<PerItemLimit>(200));
const std::vector<std::unique_ptr<Rule>> none;
std::cout << "+60: " << try_adjust(live, {{1, 60}}, rules) << ", item 1 has " << live.at(1) << "\n";
std::cout << "+50: " << try_adjust(live, {{1, 50}}, rules) << ", item 1 has " << live.at(1) << "\n";
std::cout << "+60 then -60: " << try_adjust(live, {{1, 60}, {1, -60}}, rules) << ", item 1 has " << live.at(1) << "\n";
std::cout << "+800 without the rule: " << try_adjust(live, {{1, 800}}, none) << ", item 1 has " << live.at(1) << "\n";
return 0;
}+60: rule_rejected, item 1 has 150
+50: ok, item 1 has 200
+60 then -60: rule_rejected, item 1 has 200
+800 without the rule: ok, item 1 has 1000The +50 case lands exactly on the limit and is accepted, which kills a >= mutant. The third batch would end back at 200, but its first step reaches 260, which is a valid quantity and a policy violation, so it is rejected at the first change, the same per-event timing as TotalLimit. The last line shows the policy is the only thing stopping 1000: with an empty rule list, the engine's own range is the limit. PerItemLimit needed no change to try_adjust, which is the test of a good extension point. The final lesson asks you to design a whole engine of your own.
Optional local setup
Download the typed event engine. It contains the maintained implementation, header and template, application, runtime tests, compile-contract tests, mutation manifest, sample input and README. Browser edits are not included; copy your extension into the extracted files to keep it.
Install a C++20-capable Clang or GCC compiler. In a POSIX terminal inside the extracted folder:
c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror main.cpp engine.cpp -o event-engine
./event-engine < sample-input.txt
c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror test_engine.cpp engine.cpp -o test-engine
./test-engine
c++ -std=c++20 -fsyntax-only compile_contracts.cpp-Wall -Wextra -Wpedantic turn on the common warnings, and -Werror makes any warning stop the build, so a warning cannot scroll past unread.
The application and the runtime tests have separate main functions, so build them separately. Keep assertions enabled by not defining NDEBUG. Windows may add .exe; use the MSYS2 terminal for these shell commands. The two reject_*.cpp files intentionally fail compilation; do not compile every source file together.
Going further
Compile reject_predicate.cpp and reject_copy.cpp separately with -fsyntax-only and confirm each fails for its intended reason. With a supporting toolchain, add -g -fsanitize=address,undefined -fno-omit-frame-pointer to the runtime-test build. Use a debugger to inspect the staged and live inventories just before a rejected batch returns. Exceptions, concurrency, coroutines and custom allocators need additional contracts and are outside this browser project.
Completion is saved in this browser only. It does not measure mastery.