Skip to content

Give Each Event Its Own Data

The Course
•
35 min study

Intermediate C++ taught validated classes, maps, stable IDs, algorithms, explicit results, moves and borrowed views. Advanced C++ combines those tools in a reusable event engine that you finish on Day 7. C is not a prerequisite.

The engine receives events: requests to change an inventory. A Create needs an ID, a name and a starting quantity. An Adjust needs an ID and a signed delta. A Rename needs an ID and a replacement name. The tempting first design is one record with every field and a kind string that says which fields matter. That design compiles, and it quietly invites bugs: an Adjust has a name nobody sets, a Create has a delta nobody reads, and nothing stops code from reading the wrong one. This lesson gives each event its own type, so the compiler knows which fields exist for which operation.

Predict and run

Predict the output, then run it.

Predict before running C++
#include <iostream>
#include <string>

struct Create { int id; std::string name; int quantity; };

int main() {
    Create event{2,"Bolts",10};
    std::cout << event.id << " " << event.name << " " << event.quantity << "\n";
    return 0;
}
Check your prediction
Text
2 Bolts 10

Create is an aggregate: a struct with public members, no user-declared constructors and no virtual functions. Brace initialization fills the members in declaration order, so 2 goes to id, "Bolts" to name and 10 to quantity. Swap the order of name and quantity in the struct and the same braces stop compiling, because "Bolts" cannot initialize an int. Swap id and quantity instead and it still compiles, silently giving you item 10 with quantity 2. That gap is what the next sections close.

The one-record design and its failure

Here is the fat record. Every operation uses the same struct, and the meaning of each field depends on kind.

One record for every operation C++
#include <iostream>
#include <string>

struct Record {
    std::string kind;
    int id = 0;
    std::string name;
    int quantity = 0;
    int delta = 0;
};

int change(const Record& record) {
    if (record.kind == "create") { return record.quantity; }
    if (record.kind == "adjust") { return record.quantity; } // Wrong field, still compiles.
    return 0;
}

int main() {
    Record adjust{"adjust", 2, "", 0, -3};
    Record typo{"Adjust", 2, "", 0, -3};
    std::cout << change(adjust) << " " << change(typo) << "\n";
    return 0;
}
Text
0 0

Both answers should be -3. The first is wrong because change read quantity for an Adjust, a field that exists for every record and is always zero here. The second is wrong because "Adjust" is not "adjust", and a string comparison cannot know which spellings are legal. Neither mistake produces a warning, because to the compiler every field is valid for every record. Tests might catch them; the type system never will.

One type per operation

Give each operation its own struct. Now an Adjust simply has no name and no quantity, so code that reads them does not compile.

Separate event types C++
#include <iostream>
#include <string>

struct Create { int id; std::string name; int quantity; };
struct Adjust { int id; int delta; };
struct Rename { int id; std::string name; };

int change(const Create& event) { return event.quantity; }
int change(const Adjust& event) { return event.delta; }
int change(const Rename&) { return 0; }

int main() {
    Create create{.id = 2, .name = "Bolts", .quantity = 10};
    Adjust adjust{.id = 2, .delta = -3};
    Rename rename{.id = 2, .name = "Steel bolts"};
    std::cout << change(create) << " " << change(adjust) << " " << change(rename) << "\n";
    return 0;
}
Text
10 -3 0

Two C++ features carry the design. Overloading picks a change function by the argument's type, so the choice of behavior is made by the compiler instead of by a string comparison at run time. Designated initializers, new in C++20, name each field at the construction site. Adjust{.id = 2, .delta = -3} cannot be read the wrong way, and ISO C++ requires the designators in declaration order, so a reordered struct is flagged everywhere it is used: GCC rejects an out-of-order list outright, and Clang (the browser editor's compiler) warns with -Wreorder-init-list, which a strict build turns into an error. The Rename overload leaves its parameter unnamed, because a named but unused parameter is a warning under -Wextra, and a strict local build (-Wall -Wextra -Werror) treats warnings as errors.

Events own their data

Each event stores its name as std::string, not std::string_view or const char*. An event may sit in a batch long after the input line it came from is gone, so it must own its characters. A view member would make the event a borrower, and its lifetime would depend on storage the event cannot see:

C++
#include <string>
#include <string_view>

struct RenameView { int id; std::string_view name; };

RenameView read_rename() {
    std::string line = "Steel bolts";
    return RenameView{2, line}; // The view points into line, which dies here.
}

Reading name from the returned value is undefined behavior: the characters were destroyed when line left scope. Undefined behavior means the language makes no promise at all. The program may print the right text today and garbage after an unrelated change, because the optimizer is allowed to assume it never happens. Owning values remove the question entirely, at the cost of a copy you can afford. You will meet views again on Day 5, where they are used only inside a single call.

Types are not validation

Distinct types make the shape of a request correct: an Adjust always has an ID and a delta. They do not make the values correct. Adjust{.id = -5, .delta = 5000} is a perfectly good Adjust object. That is deliberate. These structs have no class invariant, because an event is a request that may be refused, and the engine must be able to hold an invalid request long enough to report which one failed. The invariants live in the engine's inventory: IDs in 1..9999, quantities in 0..1000, names of 1 to 40 printable characters. Put checks where the invariant belongs, and keep the event types as plain, cheap-to-copy data with public fields.

Practice

Exercise

Your turn

Define Create, Adjust and Rename with the fields above. Write three overloads of std::string describe(const T&) that each return a one-line description, then construct one of each with designated initializers and print:

Shell
create 2 Bolts 10
adjust 2 -3
rename 2 Steel bolts
Your workspace C++
#include <iostream>
#include <string>

// Define the three event types and three describe overloads.

int main() {
    // Construct one event of each type and print its description.
    return 0;
}
Hint 1: the idea

Each overload knows exactly which fields its type has, so it can only read fields that exist.

Hint 2: a first step

Build the text with + and std::to_string: "adjust " + std::to_string(event.id) + " " + std::to_string(event.delta).

Show one solution
Run the solution C++
#include <iostream>
#include <string>

struct Create { int id; std::string name; int quantity; };
struct Adjust { int id; int delta; };
struct Rename { int id; std::string name; };

std::string describe(const Create& event) {
    return "create " + std::to_string(event.id) + " " + event.name + " " + std::to_string(event.quantity);
}
std::string describe(const Adjust& event) {
    return "adjust " + std::to_string(event.id) + " " + std::to_string(event.delta);
}
std::string describe(const Rename& event) {
    return "rename " + std::to_string(event.id) + " " + event.name;
}

int main() {
    std::cout << describe(Create{.id = 2, .name = "Bolts", .quantity = 10}) << "\n";
    std::cout << describe(Adjust{.id = 2, .delta = -3}) << "\n";
    std::cout << describe(Rename{.id = 2, .name = "Steel bolts"}) << "\n";
    return 0;
}
Text
create 2 Bolts 10
adjust 2 -3
rename 2 Steel bolts

Each overload reads only the fields its type declares, so a slip such as event.name inside the Adjust overload is a compile error rather than an empty string at run time. The weakness left is that the three types are still unrelated: you cannot put them in one std::vector to form a batch. The next lesson joins them into one closed type with std::variant.

Was this article helpful?

Your response is saved on this device.