A batch is a sequence of requested events that belong together. Moving five units from item 1 to item 2 is two adjustments, -5 and +5, and it only makes sense as a pair. If the engine applies the first, then rejects the second, five units have vanished from the inventory, and the caller was told "rejected", which they will reasonably read as "nothing happened". The engine's central promise is therefore that a batch is atomic: if any event in it is rejected, none of its changes stay applied.
The technique is to stage. Copy the current inventory, apply the events to the copy, and publish the copy only after every event and every rule has succeeded. Until that one moment, live state is never touched, so there is nothing to undo.
Predict and run
#include <iostream>
#include <map>
int main() {
std::map<int,int> live{{1,10}};
auto staged = live;
staged.find(1)->second += 5;
bool valid = false;
if (valid) { live.swap(staged); }
std::cout << live.find(1)->second << "\n";
return 0;
}Check your prediction
10auto staged = live; copies the whole map, so staged and live are independent from that line on. The adjustment changes only the copy. Because valid is false, the swap never happens, and live still says 10. Set valid to true and run again: it prints 15. The swap line is the only publication point in the program, which is exactly what makes the behavior easy to reason about.
The in-place version and its failure
Here is the transfer applied directly to live state, stopping at the first invalid change:
#include <iostream>
#include <map>
#include <utility>
#include <vector>
bool apply_in_place(std::map<int,int>& live, const std::vector<std::pair<int,int>>& changes) {
for (const auto& [id, delta] : changes) {
auto found = live.find(id);
if (found == live.end()) { return false; }
found->second += delta;
}
return true;
}
int main() {
std::map<int,int> live{{1, 10}, {2, 0}};
bool ok = apply_in_place(live, {{1, -5}, {3, 5}}); // Item 3 does not exist.
std::cout << "accepted " << ok << ": item 1 has " << live[1] << ", item 2 has " << live[2] << "\n";
return 0;
}accepted 0: item 1 has 5, item 2 has 0The batch was rejected, and five units are gone anyway. You could try to repair this by remembering each change and reversing it on failure, an undo log. That works, but every kind of event then needs a correct inverse, and the reversal code runs only on failure paths, which are the least tested paths in any program. Staging needs no inverses at all.
Copy, change, swap
The staged version has three steps, and each has a reason:
- Copy.
Inventory staged = state_;makes an independent value. The engine'sInventoryis astd::map<int, Item>, andItemholds astd::string, so the copy is a deep copy: no element is shared. - Change. Every event and every rule sees only
staged. A rejection simply returns, andstagedis destroyed with the function's other locals. - Swap.
state_.swap(staged);exchanges the two maps' internal pointers. It is constant time and cannot fail, which matters: a publication step that could fail halfway would reintroduce the very problem staging solves.
After the swap, staged holds the old inventory and is destroyed on return. state_ = std::move(staged); would also publish safely; the project uses swap because it reads unmistakably as "exchange, nothing else". Assignment by copy, state_ = staged;, would work too but repeats the whole copy for nothing.
This pattern gives the strong guarantee: an operation either succeeds completely or leaves the state exactly as it was. It is the same idea as the copy-and-swap idiom for assignment operators.
What staging does not cover
Be precise about the promise. Staging covers ordinary domain rejection: invalid values, missing IDs, duplicates and rule failures. It does not cover:
- Allocation failure. Copying a map allocates. With exceptions disabled, as in this course, a failed allocation ends the program rather than returning an error, so the engine makes no recovery promise for it.
- External effects. If a rule printed a line or wrote a file while inspecting
staged, discardingstageddoes not unprint the line. That is why rules must be pure. - Cost. Each batch copies the whole inventory, which is linear in its size. For an engine capped at 100 items that is trivial. A system with millions of records would choose a different design, such as an undo log or a persistent data structure that shares unchanged parts, and would pay for it in complexity.
Practice
Your turn
Write bool try_batch(std::map<int,int>& live, const std::vector<std::pair<int,int>>& changes) that applies each (id, delta) pair to a staged copy. Reject a delta outside -1000..1000, a missing ID, or a result outside 0..1000. Publish with swap only if every change succeeds. Starting from item 1 with 10 and item 2 with 0, try three batches and print the inventory after each:
transfer 5: accepted, 1:5 2:5
transfer 9: rejected, 1:5 2:5
missing item: rejected, 1:5 2:5The batches are {1,-5},{2,5}, then {2,9},{1,-9}, then {1,-1},{3,1}.
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
void print(const char* label, bool ok, const std::map<int,int>& live) {
std::cout << label << ": " << (ok ? "accepted" : "rejected") << ",";
for (const auto& [id, quantity] : live) { std::cout << " " << id << ":" << quantity; }
std::cout << "\n";
}
int main() {
std::map<int,int> live{{1, 10}, {2, 0}};
// Write try_batch, then run the three batches.
return 0;
}Hint 1: the idea
Every check and every write goes to the copy. The caller's map changes in exactly one place, at the end.
Hint 2: a first step
Begin with auto staged = live; and loop for (const auto& [id, delta] : changes), using staged.find(id), never live.find(id).
Show one solution
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
bool try_batch(std::map<int,int>& live, const std::vector<std::pair<int,int>>& changes) {
auto staged = live;
for (const auto& [id, delta] : changes) {
if (delta < -1000 || delta > 1000) { return false; }
auto found = staged.find(id);
if (found == staged.end()) { return false; }
const int next = found->second + delta;
if (next < 0 || next > 1000) { return false; }
found->second = next;
}
live.swap(staged);
return true;
}
void print(const char* label, bool ok, const std::map<int,int>& live) {
std::cout << label << ": " << (ok ? "accepted" : "rejected") << ",";
for (const auto& [id, quantity] : live) { std::cout << " " << id << ":" << quantity; }
std::cout << "\n";
}
int main() {
std::map<int,int> live{{1, 10}, {2, 0}};
print("transfer 5", try_batch(live, {{1, -5}, {2, 5}}), live);
print("transfer 9", try_batch(live, {{2, 9}, {1, -9}}), live);
print("missing item", try_batch(live, {{1, -1}, {3, 1}}), live);
return 0;
}transfer 5: accepted, 1:5 2:5
transfer 9: rejected, 1:5 2:5
missing item: rejected, 1:5 2:5In the second batch, item 2 reaches 14 in the staged copy before item 1 would drop to -4; in the third, item 1 drops to 4 before item 3 turns out to be missing. Both earlier changes were real, in the copy, and both vanished with it. The function arguments are evaluated before print reads live, so each line shows the state after its batch. Next you look at what each event sees: the staged changes made by the events before it.
Completion is saved in this browser only. It does not measure mastery.