A bool result tells a caller that a 200-event batch failed. It does not say which event, or why. The caller then has to replay the batch one event at a time to find out, or guess. The engine knows both facts at the moment it rejects, so it should return them: an error code that names the kind of failure, and the zero-based index of the event that caused it.
The project's result type is struct BatchResult { Error error; std::optional<std::size_t> index; };. Each half is a deliberate choice: a scoped enum for the kind of failure, and an optional index because some failures have no event to point at.
Predict and run
#include <iostream>
#include <optional>
enum class Error { none,invalid };
struct BatchResult { Error error; std::optional<std::size_t> index; };
int main() {
BatchResult result{Error::invalid,1};
if (result.index) { std::cout << "Failed event: " << *result.index << "\n"; }
return 0;
}Check your prediction
Failed event: 1result.index holds a value, so it tests true and *result.index reads 1: the second event failed. Change the initializer to {Error::invalid, 0} and predict. It prints Failed event: 0, because an optional holding zero is engaged; zero is the first event, not "no event". Change it to {Error::invalid, std::nullopt} and nothing prints.
Why not a sentinel
The classic alternative is a plain std::size_t with a special value, such as -1 converted to the largest size_t, meaning "no index". It works until someone forgets to check: the sentinel is a valid number, so code that prints it or uses it to index a vector compiles without complaint and produces nonsense or undefined behavior. With std::optional, the absent case is a different state of the type. You must test it or use *, and the reader sees the possibility of absence in the declaration.
std::optional also compares with plain values in a useful way. result.index == 1 is true only when the optional holds a value equal to 1, and false when it is empty, so tests can write assert(result.index == 1); without unwrapping. The project's tests do exactly that.
Which failures have an index
Two families of errors share the enum:
- Per-event failures happen while processing a specific event:
invalid,duplicate,missing,fullandrule_rejected. They always carry the index of that event. - Preflight failures happen before any event is processed. A batch of more than 256 events is rejected as
batch_too_largebefore the first event is looked at, so there is no index to report, and the result holdsstd::nullopt.
Success is {Error::none, std::nullopt}. These combinations are the type's intended states. The aggregate does not enforce them; nothing stops a caller from building {Error::none, 3}. A stricter design would make the members private and offer named constructors such as success(), failed_at(error, index) and preflight(error). The project keeps the simple aggregate and checks the combinations in tests instead, which is reasonable for a type produced in one place.
Exhaustive switches over the enum
enum class values do not convert to int implicitly and their names stay inside the enum's scope, so Error::missing cannot be confused with some other missing. A switch over an enum class gets a check similar to std::visit: a switch that handles some enumerators and has no default gets a warning for each one it misses. Clang reports it by default (it is also part of -Wall), so the browser editor shows it above the output and still runs the program:
s.cpp:3:13: warning: enumeration value 'missing' not handled in switch [-Wswitch]Under -Werror, as in the course's checker or a strict local build, the same message is an error and the build fails.
Leave out the default on purpose. A default: label silences the warning for every future enumerator, the same way a catch-all visitor hides new alternatives. Put a final return after the switch instead; the compiler needs it, because an enum object can technically hold a value that has no name.
A result is not proof of rollback
A test that checks result.error == Error::invalid && result.index == 1 proves the engine reported the right failure. It does not prove the engine discarded the staged changes. The project's mutation "mutate live state during batch" replaces Inventory staged = state_; with a reference to live state, and every error code and index stays correct. Only the assertion that compares the complete exported inventory with its value before the batch catches it. Check the report and the state, always both.
Practice
Your turn
Define enum class Error { none, invalid, missing, rule_rejected, batch_too_large }; and the BatchResult struct. Write std::string describe(const BatchResult& result) using a switch with no default, so that it returns text like the lines below. Describe four results: success, invalid at index 0, rule_rejected at index 3, and a preflight batch_too_large:
accepted
event 0: invalid value
event 3: rejected by a rule
batch rejected before processing: too large#include <iostream>
#include <optional>
#include <string>
enum class Error { none, invalid, missing, rule_rejected, batch_too_large };
struct BatchResult { Error error; std::optional<std::size_t> index; };
int main() {
// Write describe and print four results.
return 0;
}Hint 1: the idea
Split the work: a switch turns the error into a reason, and the optional decides whether the line names an event.
Hint 2: a first step
Write const char* reason(Error error) with one case per enumerator, then in describe return "event " + std::to_string(*result.index) + ": " + reason(result.error) when the index is present.
Show one solution
#include <iostream>
#include <optional>
#include <string>
enum class Error { none, invalid, missing, rule_rejected, batch_too_large };
struct BatchResult { Error error; std::optional<std::size_t> index; };
const char* reason(Error error) {
switch (error) {
case Error::none: return "accepted";
case Error::invalid: return "invalid value";
case Error::missing: return "missing item";
case Error::rule_rejected: return "rejected by a rule";
case Error::batch_too_large: return "too large";
}
return "unknown error";
}
std::string describe(const BatchResult& result) {
if (result.error == Error::none) { return reason(result.error); }
if (result.index) { return "event " + std::to_string(*result.index) + ": " + reason(result.error); }
return std::string("batch rejected before processing: ") + reason(result.error);
}
int main() {
std::cout << describe({Error::none, std::nullopt}) << "\n";
std::cout << describe({Error::invalid, 0}) << "\n";
std::cout << describe({Error::rule_rejected, 3}) << "\n";
std::cout << describe({Error::batch_too_large, std::nullopt}) << "\n";
return 0;
}accepted
event 0: invalid value
event 3: rejected by a rule
batch rejected before processing: too largeThe index-0 line is the case a sentinel design most often gets wrong, and here it is just another engaged optional. Add duplicate to the enum and reason stops compiling until you give it a message, while describe needs no change because it never lists errors. The std::string(...) in the last return matters: adding two const char* values with + does not concatenate, it does not even compile. The checkpoint next joins staging, ordering and results into one all-or-nothing batch.
Completion is saved in this browser only. It does not measure mastery.