Heuristic:1ay1 Agentty Sum Type Over Enum Fields
| Knowledge Sources | |
|---|---|
| Domains | Type_Safety, Architecture |
| Last Updated | 2026-10-28 14:00 GMT |
Overview
Model domain variants as `std::variant` (sum types) over distinct field-carrying alternatives rather than flat enums with parallel parallel arrays, so each variant carries its own data and invalid tag-field pairings are unrepresentable.
Description
The Sum_Type_Over_Enum_Fields heuristic replaces a plain enum tag plus a collection of optional/parallel fields with a `std::variant` where each alternative is a struct carrying exactly the fields that apply to that case. This eliminates the "which fields are valid for which enum value?" question — the variant type answers it structurally. A `Credential` is not an enum + six `std::optional`s; it is a variant of `ApiKey{...} | OAuthToken{...} | PatToken{...}`, and each alternative carries only the fields it needs.
In agentty this appears in: the credential domain sum type (`auth.hpp`) where each credential kind carries its own fields; the login state machine (`login.hpp`) where each modal state carries its own form data; and the capped file read result (`capped_read.hpp`) where success and error carry different payload types.
Usage
Apply this heuristic when a domain type has an enum-like discriminator with per-case fields. If the current design is `enum { A, B, C }` plus `optional<X> a_field; optional<Y> b_field;`, replace it with `variant<A_data, B_data, C_data>` where each alternative carries its own fields. This makes "A is active but b_field is set" unrepresentable.
The Insight (Rule of Thumb)
- Action: Replace `enum + optional fields` with `std::variant` of per-case structs.
- Value: Each variant alternative carries exactly the fields it needs — no invalid tag-field pairings.
- Trade-off: Slightly more verbose pattern matching (`std::visit` instead of `switch`); but eliminates "forgot to check the enum before accessing the field" bugs.
- Compatibility: Requires C++17 `std::variant` or equivalent; pairs with Heuristic:1ay1_Agentty_Unrepresentable_Invalid_State.
Reasoning
An enum-plus-optional-fields design puts the burden of "which fields are valid for which enum value" on every caller. A `switch` that forgets a case, or a caller that reads `b_field` when enum is `A`, compiles fine but crashes at runtime. A sum type moves this burden to the compiler: `std::visit` forces exhaustive handling, and each alternative only exposes the fields it actually has. The bug "read the wrong field for this enum value" becomes a type error.