Today's lessons made a promise: a rejected operation changes nothing. This checkpoint is about proving it. The difficulty is that "nothing changed" is a statement about the whole collection, and a test that inspects one field can miss a change to another. Checking size() after a duplicate insert, for example, cannot see that the duplicate replaced the original's value, because the size is the same either way.
A practical answer is to compare complete state. Give the collection a function that writes every entry as text in a fixed order, its canonical export. Save the export before an operation that should be rejected, run the operation, and compare the export again. Any change to any field of any entry makes the strings differ. The project's own tests use exactly this technique.
Predict and run
The lookup is for a missing ID, so the if body never runs. Does the whole map still equal its earlier copy?
Predict before runningC++
#include <iostream>
#include <map>
int main() {
std::map<int,int> values{{2,25}};
auto before = values;
auto found = values.find(9);
if (found != values.end()) { found->second = 10; }
std::cout << (values == before) << "\n";
return 0;
}
Check your prediction
Text
1
auto before = values; makes an independent copy, and == on two maps compares every key and value. The 1 is evidence about the entire map, not one entry. Replace find(9) with values[9] and the result becomes 0, because the read inserted a new key.
What you will use
A class with a private std::map<int, Entry>, so all changes go through its member functions.
Error valuesnone, duplicate, invalid and missing, one per reason to refuse.
emplace for adding, because it never replaces an existing key.
Validate-then-commit for edits.
A const export function returning a std::string such as 2|25|Read\n for every entry in ID order.
Plan before you type
Write export_text() const first. Every later check depends on it, so test it on its own.
Write add: validate minutes and title, then use the .second of emplace to detect a duplicate.
Write set_minutes: find, return missing at end(), validate, then assign.
In main, add two entries and save before = board.export_text().
Attempt a duplicate add, an invalid edit and an edit of a missing ID. After each, print the error and whether the export still equals before.
Finish with one valid edit and print the new export, so the test also proves the comparison can see a change.
Prove it can fail
Swap emplace for insert_or_assign in add and run: the duplicate line must now print changed, and the final export shows the replacement title. Restore it, then move the assignment in set_minutes above the range check: the invalid-edit line must print changed. Each check you wrote should fail for exactly one of these bugs. If one bug makes no line change, the test for it is missing.
Mistakes worth checking for
A duplicate silently replaces the original:add used operator[] or insert_or_assign. Use emplace and read its .second.
A rejected edit changed one field: the assignment happened before the full validation.
A missing-ID edit added an entry: the lookup used operator[].
The "unchanged" test passes even with a bug: the test compared size() or one field. Compare the full export.
Exports differ between runs: the export iterated something unordered or sorted by a key with ties. Iterate the map, which is already in ID order.
Practice
Exercise
Your turn
Write class Board with add(int id, std::string title, int minutes), set_minutes(int id, int minutes) and export_text() const, all returning an Error except the export. Titles must not be empty and minutes are 1 through 180. Start from task 2 (Read, 25) and task 9 (Review, 10). Print:
Text
add duplicate 2: duplicate, unchangedset 9 to 0: invalid, unchangedset 4 to 30: missing, unchangedset 9 to 15: none, changed2|25|Read9|15|Review
Insertion and replacement have different contracts. Save the export before each operation and compare it afterward; that single comparison covers every field of every task.
Hint 2: a first step
Write add and export_text first and nothing else. Add the two starting tasks and print the export; you should see 2|25|Read and 9|10|Review. Then add the duplicate check and its line of output, comparing the export before and after the call.
add duplicate 2: duplicate, unchangedset 9 to 0: invalid, unchangedset 4 to 30: missing, unchangedset 9 to 15: none, changed2|25|Read9|15|Review
Each check reports both halves of the contract, the returned error and the full state, so a function that returns the right error but changes data anyway is caught. The last line proves the comparison is sensitive: a valid edit does show as changed. If the two setup add calls failed, main returns 1 instead of testing from a wrong starting state. Day 5 asks who owns the strings and containers inside a class like Board, and what happens to them on copy, move and destruction.
Inspect the tracker tests
The project's test file uses the same technique on the real tracker. Run it, then read it.
Before you run it, predict what it prints: should any assertion stop the unmodified project, and if not, what is the last line?
Tracker contractsC++#include "tracker.h"
#include <cassert>
#include <iostream>
#include <sstream>
int main() {
assert(!Task::create(0, "Read", 25, State::todo));
assert(!Task::create(10000, "Read", 25, State::todo));
assert(!Task::create(1, "", 25, State::todo));
assert(!Task::create(1, " Read", 25, State::todo));
assert(!Task::create(1, "Read ", 25, State::todo));
assert(!Task::create(1, "Bad|title", 25, State::todo));
assert(!Task::create(1, "Read", 0, State::todo));
assert(!Task::create(1, "Read", 181, State::todo));
assert(Task::create(9999, std::string(40, 'x'), 180, State::done));
assert(!Task::create(1, std::string(41, 'x'), 25, State::todo));
Tracker tracker;
assert(tracker.size() == 0 && !tracker.find(1));
auto first = Task::create(2, "Read", 25, State::todo);
auto second = Task::create(1, "Review", 10, State::done);
auto third = Task::create(3, "Practice", 25, State::todo);
assert(first && second && third);
assert(tracker.add(*first) == Error::none);
assert(tracker.add(*second) == Error::none);
assert(tracker.add(*third) == Error::none);
const std::string original = export_tasks(tracker);
assert(original == "1|10|done|Review\n2|25|todo|Read\n3|25|todo|Practice\n");
assert(tracker.add(*first) == Error::duplicate && export_tasks(tracker) == original);
assert(tracker.edit(2, "Changed", 0, State::done) == Error::invalid);
assert(export_tasks(tracker) == original);
assert(tracker.edit(99, "Missing", 20, State::todo) == Error::missing);
assert(tracker.complete(99) == Error::missing);
auto copy = tracker.find(2);
assert(copy && copy->edit("Copy", 50, State::done));
assert(tracker.find(2)->title() == "Read");
auto ordered = report_order(tracker);
assert(ordered[0].id() == 2 && ordered[1].id() == 3 && ordered[2].id() == 1);
assert(export_tasks(tracker) == original);
assert(total_minutes_if(ordered, [](const Task&) { return true; }) == 60);
assert(total_minutes_if(ordered, [](const Task& t) { return t.state() == State::todo; }) == 50);
assert(tracker.complete(2) == Error::none);
assert(tracker.complete(2) == Error::none);
assert(total_minutes_if(tracker.snapshot(), [](const Task& t) { return t.state() == State::todo; }) == 25);
assert(tracker.edit(2, "Updated", 40, State::todo) == Error::none);
assert(tracker.find(2)->title() == "Updated" && tracker.find(2)->minutes() == 40);
assert(tracker.find(2)->state() == State::todo);
const std::string canonical = export_tasks(tracker);
Tracker restored;
std::istringstream input(canonical);
std::string line;
while (std::getline(input, line)) {
auto result = parse_task(line);
assert(result.task && result.error == Error::none);
assert(restored.add(*result.task) == Error::none);
}
assert(export_tasks(restored) == canonical);
const std::vector<std::string> invalid{"", "1|25|todo", "1|25|later|Read", "1|25x|todo|Read",
"1|25|todo|Read|extra", "1|999999999999999999999|todo|Read", "-1|25|todo|Read", "1|25|todo|"};
for (const auto& text : invalid) { assert(!parse_task(text).task); }
assert(parse_task("bad").error == Error::malformed);
assert(parse_task("0|25|todo|Read").error == Error::invalid);
Task owned = *parse_task(std::string("9|1|todo|Temporary")).task;
assert(owned.title() == "Temporary");
assert(tracker.remove(1) == Error::none && !tracker.find(1));
assert(tracker.remove(1) == Error::missing);
assert(tracker.find(2)->id() == 2 && tracker.find(3)->id() == 3);
// A removed ID is free again: the brief promises no renumbering, not that IDs are retired.
assert(tracker.add(*Task::create(1, "Plan", 15, State::todo)) == Error::none);
assert(tracker.find(1)->title() == "Plan" && tracker.size() == 3);
assert(tracker.remove(1) == Error::none);
Tracker full;
for (int id = 1; id <= 1000; ++id) { assert(full.add(*Task::create(id, "Task", 180, State::todo)) == Error::none); }
assert(full.add(*Task::create(1001, "Extra", 1, State::todo)) == Error::full && full.size() == 1000);
assert(total_minutes_if(full.snapshot(), [](const Task&) { return true; }) == 180000L);
assert(export_tasks(Tracker{}).empty());
std::cout << "Tracker checks passed\n";
}
#include "tracker.h"
#include <algorithm>
#include <sstream>
#include <utility>
static bool valid_fields(const std::string& title, int minutes, State state) {
if (title.empty() || title.size() > 40 || minutes < 1 || minutes > 180 ||
(state != State::todo && state != State::done)) { return false; }
if (title.front() == ' ' || title.back() == ' ') { return false; }
for (unsigned char ch : title) {
if (ch < 32 || ch > 126 || ch == '|') { return false; }
}
return true;
}
Task::Task(int id, std::string title, int minutes, State state)
: id_(id), title_(std::move(title)), minutes_(minutes), state_(state) { }
std::optional<Task> Task::create(int id, std::string title, int minutes, State state) {
if (id < 1 || id > 9999 || !valid_fields(title, minutes, state)) { return std::nullopt; }
return Task(id, std::move(title), minutes, state);
}
bool Task::edit(std::string title, int minutes, State state) {
if (!valid_fields(title, minutes, state)) { return false; }
title_ = std::move(title);
minutes_ = minutes;
state_ = state;
return true;
}
static std::optional<int> decimal(std::string_view text) {
if (text.empty()) { return std::nullopt; }
for (char ch : text) { if (ch < '0' || ch > '9') { return std::nullopt; } }
std::istringstream input{std::string(text)};
int value = 0;
if (!(input >> value)) { return std::nullopt; }
return value;
}
ParseResult parse_task(std::string_view line) {
const auto first = line.find('|');
if (first == std::string_view::npos) { return {std::nullopt, Error::malformed}; }
const auto second = line.find('|', first + 1);
if (second == std::string_view::npos) { return {std::nullopt, Error::malformed}; }
const auto third = line.find('|', second + 1);
if (third == std::string_view::npos || line.find('|', third + 1) != std::string_view::npos) {
return {std::nullopt, Error::malformed};
}
auto id = decimal(line.substr(0, first));
auto minutes = decimal(line.substr(first + 1, second - first - 1));
auto state_text = line.substr(second + 1, third - second - 1);
if (!id || !minutes || (state_text != "todo" && state_text != "done")) {
return {std::nullopt, Error::invalid};
}
auto task = Task::create(*id, std::string(line.substr(third + 1)), *minutes,
state_text == "todo" ? State::todo : State::done);
if (!task) { return {std::nullopt, Error::invalid}; }
return {std::move(task), Error::none};
}
Error Tracker::add(const Task& task) {
if (!Task::create(task.id(), task.title(), task.minutes(), task.state())) { return Error::invalid; }
if (tasks_.find(task.id()) != tasks_.end()) { return Error::duplicate; }
if (tasks_.size() >= 1000) { return Error::full; }
tasks_.emplace(task.id(), task);
return Error::none;
}
Error Tracker::edit(int id, std::string title, int minutes, State state) {
auto it = tasks_.find(id);
if (it == tasks_.end()) { return Error::missing; }
return it->second.edit(std::move(title), minutes, state) ? Error::none : Error::invalid;
}
Error Tracker::complete(int id) {
auto it = tasks_.find(id);
if (it == tasks_.end()) { return Error::missing; }
it->second.edit(it->second.title(), it->second.minutes(), State::done);
return Error::none;
}
Error Tracker::remove(int id) {
return tasks_.erase(id) == 0 ? Error::missing : Error::none;
}
std::optional<Task> Tracker::find(int id) const {
auto it = tasks_.find(id);
if (it == tasks_.end()) { return std::nullopt; }
return it->second;
}
std::vector<Task> Tracker::snapshot() const {
std::vector<Task> result;
for (const auto& entry : tasks_) { result.push_back(entry.second); }
return result;
}
std::vector<Task> report_order(const Tracker& tracker) {
auto tasks = tracker.snapshot();
std::sort(tasks.begin(), tasks.end(), [](const Task& a, const Task& b) {
if (a.minutes() != b.minutes()) { return a.minutes() > b.minutes(); }
return a.id() < b.id();
});
return tasks;
}
std::string export_tasks(const Tracker& tracker) {
std::ostringstream output;
for (const Task& task : tracker.snapshot()) {
output << task.id() << '|' << task.minutes() << '|'
<< (task.state() == State::todo ? "todo" : "done") << '|' << task.title() << '\n';
}
return output.str();
}
#ifndef TASK_TRACKER_H
#define TASK_TRACKER_H
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
enum class State { todo, done };
enum class Error { none, malformed, invalid, duplicate, missing, full };
class Task {
public:
static std::optional<Task> create(int id, std::string title, int minutes, State state);
int id() const { return id_; }
const std::string& title() const { return title_; } // Borrowed until this task changes/dies.
int minutes() const { return minutes_; }
State state() const { return state_; }
bool edit(std::string title, int minutes, State state); // Invalid edits preserve all fields.
private:
Task(int id, std::string title, int minutes, State state);
int id_;
std::string title_;
int minutes_;
State state_;
};
struct ParseResult { std::optional<Task> task; Error error = Error::none; };
// id|minutes|todo-or-done|title. Numeric fields contain decimal digits only.
// CRLF stripping belongs to the input adapter. No embedded control characters.
ParseResult parse_task(std::string_view line);
class Tracker {
public:
Error add(const Task& task); // 1000 tasks maximum; duplicates leave existing task unchanged.
Error edit(int id, std::string title, int minutes, State state);
Error complete(int id); // Repeating completion succeeds without changing totals twice.
Error remove(int id);
std::optional<Task> find(int id) const; // Returns an owning copy.
std::vector<Task> snapshot() const; // ID order; owning values.
std::size_t size() const { return tasks_.size(); }
private:
std::map<int, Task> tasks_;
};
// Owns its return value. Input text/view may be destroyed after parsing.
std::string export_tasks(const Tracker& tracker);
std::vector<Task> report_order(const Tracker& tracker); // Minutes descending, then ID ascending.
template<class Predicate>
long total_minutes_if(const std::vector<Task>& tasks, Predicate matches) {
long total = 0;
for (const Task& task : tasks) {
if (matches(task)) { total += task.minutes(); }
}
return total;
}
#endif
Check your prediction
Text
Tracker checks passed
Find const std::string original = export_tasks(tracker); and the assertions after it. The duplicate add and the invalid edit each check the returned Errorand that export_tasks(tracker) == original. Notice also that the expected export is written out as a literal string first: if export itself were broken, comparing it only with itself would hide the bug. The later lessons explain the borrowed views and the small template these project tests use.
Completion is saved in this browser only. It does not measure mastery.