Multiplicity and lifecycle
What you will learn on this page
Section titled “What you will learn on this page”- How to state a relationship’s multiplicity: how many objects can be at each end.
- How each multiplicity chooses a C++ type: a plain member,
std::optional, a container, or a container with a rule. - How to describe an object’s lifecycle as a small set of states, and which operations are allowed in each.
- How to decide who creates and who destroys each object.
Multiplicity: how many?
Section titled “Multiplicity: how many?”The relationships lesson asked what kind of connection two classes have. Multiplicity asks how many: for one order, how many customers, lines, coupons? The common answers have short names:
| Multiplicity | Read as | Example (for one order) |
|---|---|---|
1 |
exactly one | the customer who placed it |
0..1 |
zero or one | a discount coupon |
0..* |
zero or more | lines, while the order is still being written |
1..* |
one or more | lines, once the order is placed |
n..m |
between n and m | (rare) “up to 3 delivery addresses” |
Each multiplicity is a rule. “Exactly one customer” means an order with no customer is invalid, and so is one with two. Getting the multiplicity right is the first step to choosing a C++ type that makes the wrong number impossible, or at least hard.
From multiplicity to C++ type
Section titled “From multiplicity to C++ type”| Multiplicity | Owned (composition) | Referred to (association) |
|---|---|---|
1 |
a value member, set by the constructor | an ID member, or a reference/pointer that is never null |
0..1 |
std::optional<T> |
std::optional<Id>, or a pointer that may be null |
0..* |
std::vector<T>, std::map<K, T>, … |
a container of IDs or non-owning pointers |
1..* |
a container, plus a rule that it is never empty | the same, plus the rule |
n..m |
std::array<T, n> if fixed, otherwise a container and a rule |
the same |
Three things stand out:
1and0..1are different types. A plain member cannot be “missing”, so it fits1.std::optionalsays in the type that the value may be absent, and every reader must check. Using a plain member with a special “no value” (an empty string, a-1) for0..1hides the check.0..*and1..*are the same type. No standard container means “never empty”. The difference is a rule that the class must protect in every function that adds or removes elements. That rule is an invariant, which the next lesson is about.- Choose the container by how it is used.
std::vectorfor a list in order;std::maporstd::unordered_mapfor lookup by key; the containers lesson compares their costs.
The example: an online order
Section titled “The example: an online order”An online shop’s order belongs to one customer. While the customer is still choosing, the order is a draft: lines can be added and removed, and one coupon applied. When the customer checks out, the order is placed, and can no longer be changed. The warehouse ships it, with a tracking number. Until it ships, it can be cancelled.
The parts
Section titled “The parts”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One line of an order: which item, how many, and the price of one. Money is// in whole cents in a 64-bit integer, so sums are exact. A plain struct: the// Order checks the quantity and price before it creates a line.struct OrderLine { std::string sku; // the item's stock code int quantity = 1; std::int64_t unit_price_cents = 0;
// The line's cost: quantity times unit price. The int quantity is // converted to std::int64_t for the multiplication, so it is done in // 64 bits. [[nodiscard]] std::int64_t total_cents() const noexcept { return quantity * unit_price_cents; }};
// A discount code. Order::apply_coupon refuses a percent_off outside 1..100.struct Coupon { std::string code; int percent_off = 0; // 1 to 100};
// The four stages of an order's life. A new order is a draft; shipped and// cancelled are final.enum class OrderState { draft, placed, shipped, cancelled };// The state's name as text, such as "placed", for printing and for error// messages.[[nodiscard]] std::string_view to_string(OrderState state) noexcept;OrderLine and Coupon are small values. OrderState lists the four states
of an order’s lifecycle.
The order
Section titled “The order”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Invariants:// - placed or shipped: at least one line;// - tracking number present exactly when shipped;// - lines, coupon: changed only while draft.// A call made in the wrong state throws std::logic_error and changes nothing.//// One customer's order. It owns its lines, coupon, and tracking number, and// moves through its lifecycle only by place, ship, and cancel. Each data// member's type matches its multiplicity: a plain member for exactly 1,// std::optional for 0..1, std::vector for 0..*.class Order {public: // The only way to make an Order needs a CustomerId, so an order without // a customer cannot exist. It starts as an empty draft. explicit Order(CustomerId customer) noexcept : customer_(customer) {}
[[nodiscard]] CustomerId customer() const noexcept { return customer_; } [[nodiscard]] OrderState state() const noexcept { return state_; } [[nodiscard]] const std::vector<OrderLine>& lines() const noexcept { return lines_; } [[nodiscard]] const std::optional<Coupon>& coupon() const noexcept { return coupon_; } // Empty (no value) until the order is shipped. [[nodiscard]] const std::optional<std::string>& tracking() const noexcept { return tracking_; } // The sum of the lines' totals, less the coupon's percentage if there is // one (the discount is rounded down to a whole cent). [[nodiscard]] std::int64_t total_cents() const;
// While draft. Adding an item already in the order adds to its quantity. // (The line keeps the price it was first added with.) // Throws std::invalid_argument if quantity <= 0 or the price is negative. // "While draft" means: in any other state it throws std::logic_error. void add_line(std::string sku, int quantity, std::int64_t unit_price_cents); // While draft. Returns false if no line has this sku. // std::string_view lets a caller pass a string literal or a std::string // without making a copy; the function only reads it. bool remove_line(std::string_view sku); // While draft. Replaces any earlier coupon. // Throws std::invalid_argument unless 1 <= percent_off <= 100. void apply_coupon(Coupon coupon);
// The transitions. Each throws std::logic_error, changing nothing, when // called in a state that does not allow it. void place(); // draft -> placed; needs at least one line void ship(std::string tracking); // placed -> shipped void cancel(); // draft or placed -> cancelled
private: // Throws std::logic_error, with a message such as "cannot change an // order that is placed", unless the order is in the `expected` state. void require(OrderState expected, std::string_view action) const;
CustomerId customer_; // exactly 1, fixed for life OrderState state_ = OrderState::draft; // every order starts as a draft std::vector<OrderLine> lines_; // 0..* while draft, 1..* after std::optional<Coupon> coupon_; // 0..1 std::optional<std::string> tracking_; // 0..1: present exactly when shipped};Each member’s type comes from its multiplicity, and its comment says which:
- Customer, exactly 1. A
CustomerId, set by the constructor, with no setter. An order cannot be created without one, and it never changes. It is an ID, not a pointer, because orders are stored for years, long after anyCustomerobject in memory is gone. - Lines, 0..* then 1..*. A
std::vector<OrderLine>, owned by value. While the order is a draft, zero lines is fine: the customer has not chosen yet.placerefuses an empty order, so a placed order always has at least one. The multiplicity depends on the state. - Coupon, 0..1.
std::optional<Coupon>.apply_couponreplaces any earlier one, so there can never be two. - Tracking number, 0..1, present exactly when shipped. Another
std::optional, set only byship.
Who creates, who destroys
Section titled “Who creates, who destroys”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Adds `quantity` of an item. Both checks come before any change, so a// refused call leaves the order as it was. Then there are two cases: the// item is already in the order (add to that line), or it is new (create a// line). Merging means each sku appears on at most one line.void Order::add_line(std::string sku, int quantity, std::int64_t unit_price_cents) { require(OrderState::draft, "change"); // throws unless the order is a draft if (quantity <= 0 || unit_price_cents < 0) { throw std::invalid_argument("Order::add_line: bad quantity or price"); } // std::find_if walks the lines from the first and stops at the first one // the lambda says yes to: here, the line with the same sku. [&] lets the // lambda read `sku` without copying it. The result is an iterator, a // position in the vector; lines_.end() (one past the last line) means // "not found". const auto same = std::find_if(lines_.begin(), lines_.end(), [&](const OrderLine& line) { return line.sku == sku; }); if (same != lines_.end()) { // `same->` reaches the line the iterator points at. The new price is // not used: the line keeps the price it already had. same->quantity += quantity; return; } // A new item. {...} builds an OrderLine in field order; the sku string is // moved in, not copied, because add_line took its own copy by value. lines_.push_back({std::move(sku), quantity, unit_price_cents}); // the order creates its lines}
// Removes the line for this sku, if there is one. std::erase_if (C++20)// removes every element the lambda says yes to and returns how many it// removed; because of the merging in add_line, that is 0 or 1. `> 0` turns// the count into "was anything removed?". Removing the last line is allowed:// a draft may be empty, and place() is what refuses an empty order.bool Order::remove_line(std::string_view sku) { require(OrderState::draft, "change"); return std::erase_if(lines_, [&](const OrderLine& line) { return line.sku == sku; }) > 0;}How this code works: Order::add_line and remove_line
add_line runs in three stages.
- Is a change allowed at all?
require(OrderState::draft, "change")throwsstd::logic_errorunless the order is a draft. - Are the numbers sensible? A quantity of zero or less, or a negative
price, throws
std::invalid_argument. Both checks come before any change, so a refused call leaves the order as it was. - Merge or create.
std::find_iflooks for a line with the samesku. If it finds one,samepoints at it and its quantity grows. If not,sameequalslines_.end(), and a newOrderLineis added at the back.
A worked example: the three calls in main below.
| Call | Line found by find_if? |
What happens | Lines afterwards |
|---|---|---|---|
add_line("PEN-01", 3, 150) |
no (no lines yet) | new line | PEN-01 × 3 |
add_line("PAD-A4", 1, 400) |
no | new line | PEN-01 × 3, PAD-A4 × 1 |
add_line("PEN-01", 2, 150) |
yes, the first line | its quantity goes from 3 to 5 | PEN-01 × 5, PAD-A4 × 1 |
When a line is found, the price passed in is not used: the line keeps the price it was first added with. Here both prices are 150, so it makes no difference.
remove_line uses std::erase_if, which removes every line whose sku
matches and returns how many it removed. Because add_line merges, that count
is 0 or 1, and > 0 turns it into the bool result.
The order creates its own lines: callers pass the item, quantity, and price,
and add_line builds the OrderLine. Callers never hold a line of their own.
That gives the order control over its parts. It can merge two additions of the
same item into one line, and check the quantity and price before a line exists.
The lines are destroyed with the order, or when remove_line erases them.
The order itself is created by whoever starts a purchase (here, main), and
destroyed by whoever owns it. In a real shop that would be a store of orders,
such as a std::unordered_map<OrderId, Order> or a database. The customer
is never created or destroyed by the order: the order only knows the ID.
A useful way to settle these questions for each class:
- Who creates it? Usually the object that owns it, or a factory function that returns it.
- Who owns it? Exactly one owner for composition. If you cannot name one,
reconsider the relationship before reaching for
std::shared_ptr. - Who destroys it, and when? With RAII, “when its owner is destroyed”, or when the owner removes it.
- Who refers to it, and what happens to them when it is destroyed? IDs survive; pointers and references dangle.
Lifecycle: states and transitions
Section titled “Lifecycle: states and transitions”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each transition checks first and changes last, so a refused call throws// and leaves the order exactly as it was.
// draft -> placed. This is the one place the "at least one line" rule is// checked: after it, no function can change the lines, so it stays true.void Order::place() { require(OrderState::draft, "place"); if (lines_.empty()) { throw std::logic_error("cannot place an order with no lines"); } state_ = OrderState::placed;}
// placed -> shipped. The tracking number and the state change together,// which keeps "tracking present exactly when shipped" true. The string is// moved into the std::optional, which then holds a value.void Order::ship(std::string tracking) { require(OrderState::placed, "ship"); tracking_ = std::move(tracking); state_ = OrderState::shipped;}
// draft or placed -> cancelled. Two states are allowed, so require() (which// takes one) does not fit, and the check is written out: refuse unless the// state is draft or placed. Cancelling a cancelled order is refused too.void Order::cancel() { if (state_ != OrderState::draft && state_ != OrderState::placed) { throw std::logic_error("cannot cancel an order that is " + std::string(to_string(state_))); } state_ = OrderState::cancelled;}Text description of the diagram
An order starts as a draft when it is constructed for a customer. While it is a
draft, add_line, remove_line, and apply_coupon change it, and it stays a
draft. place moves a draft to placed, but only if it has at least one line.
cancel moves a draft to cancelled. From placed, ship with a tracking number
moves it to shipped, and cancel moves it to cancelled. Shipped and cancelled
are final: no operation leaves them. Any operation not listed for a state is
refused.
Diagram source (Mermaid)
stateDiagram-v2
[*] --> Draft : Order(customer)
Draft --> Draft : add_line, remove_line, apply_coupon
Draft --> Placed : place [at least one line]
Draft --> Cancelled : cancel
Placed --> Shipped : ship(tracking)
Placed --> Cancelled : cancel
Shipped --> [*]
Cancelled --> [*]A lifecycle is the set of states an object goes through, and the operations that move it between them. Writing it down, as a diagram or a table, answers questions that are easy to leave vague:
- Which operations are allowed in each state? Lines change only in draft.
- Which operations change the state? Only
place,ship, andcancel. - Which states are final? Shipped and cancelled.
- What happens to a call in the wrong state? Here:
std::logic_error, and nothing changes. The caller asked for something the order’s rules forbid, which the errors lesson classes as a caller mistake. Callers that might be in doubt can checkstate()first.
Each rule about the parts is tied to a state: “at least one line” applies while the
order is placed or shipped (a draft cancelled with no lines stays empty, and
that is fine); “has a tracking number” applies exactly in shipped. The class
checks the rule at the one transition that enters the state (place checks the
lines; ship sets the tracking number) and refuses every change that could
break it later (no line changes after draft).
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A draft order for customer 7. Prices are in cents: 150 is $1.50.Order order{CustomerId{7}};order.add_line("PEN-01", 3, 150);order.add_line("PAD-A4", 1, 400);order.add_line("PEN-01", 2, 150); // the same item again: one line, quantity 5order.apply_coupon({"SPRING10", 10}); // builds a Coupon: code, 10% off
// print_cents (above main) prints cents as dollars, such as $1.50.for (const OrderLine& line : order.lines()) { std::cout << line.sku << " x" << line.quantity << " at "; print_cents(line.unit_price_cents); std::cout << '\n';}// coupon() returns the std::optional; `->code` reads the Coupon inside.// Safe here because a coupon was applied above.std::cout << "total with " << order.coupon()->code << ": ";print_cents(order.total_cents());std::cout << '\n';
order.place();std::cout << "state: " << to_string(order.state()) << '\n';order.ship("TRK-123"); // `*order.tracking()` below: the string inside the optionalstd::cout << "state: " << to_string(order.state()) << ", tracking " << *order.tracking() << '\n';
// A shipped order cannot be cancelled: cancel throws std::logic_error.// try/catch catches it here, and error.what() gives its message.try { order.cancel();} catch (const std::logic_error& error) { std::cout << "refused: " << error.what() << '\n';}PEN-01 x5 at $1.50PAD-A4 x1 at $4.00total with SPRING10: $10.35state: placedstate: shipped, tracking TRK-123refused: cannot cancel an order that is shippedThe total is 5 × $1.50 + $4.00 = $11.50, less 10% ($1.15): $10.35.
The order and its parts in one drawing
Section titled “The order and its parts in one drawing”First the entity sketch: what an order is connected to, and how many of each.
Text description of the diagram
Four boxes. A dashed arrow from Order to Customer, labelled “knows 1 customer,
by ID”: each order refers to exactly one customer, by ID, without owning it.
A solid arrow from Order to OrderLine, labelled “owns 0..* lines”: an order
holds any number of lines (one or more once placed, a rule the sketch cannot
show). A solid arrow from Order to Coupon, labelled “owns 0..1”: an order holds
at most one coupon. Lines and coupons belong to one order each. A customer can
have any number of orders; the sketch shows that in the text, not as an arrow,
because Customer has no member for its orders.
Diagram source (Mermaid)
flowchart LR
Order -.->|knows 1 customer, by ID| Customer
Order -->|"owns 0..* lines"| OrderLine
Order -->|owns 0..1| CouponThen the class outline. Each multiplicity in the sketch becomes a C++ type:
class Order
one customer's order, from draft to shipped or cancelled
Data members
CustomerId customer_;exactly 1, fixed for lifeOrderState state_;draft at the startstd::vector<OrderLine> lines_;0..* while draft, 1..* after place()std::optional<Coupon> coupon_;0..1std::optional<std::string> tracking_;present exactly when shipped
Member functions
explicit Order(CustomerId customer);OrderState state() const;std::int64_t total_cents() const;void add_line(std::string sku, int quantity, std::int64_t unit_price_cents);bool remove_line(std::string_view sku);void apply_coupon(Coupon coupon);void place();draft to placed; needs at least one linevoid ship(std::string tracking);placed to shippedvoid cancel();draft or placed to cancelled
struct OrderLine
Data members
std::string sku;int quantity = 1;std::int64_t unit_price_cents = 0;
Member functions
std::int64_t total_cents() const;
struct Coupon
Data members
std::string code;int percent_off = 0;1 to 100
enum class OrderState
Values
draftplacedshippedcancelled
| Multiplicity | C++ type in the outline | What the type guarantees |
|---|---|---|
| exactly 1 | CustomerId customer_ (a plain member) |
always present; set by the constructor |
| 0..1 | std::optional<Coupon> coupon_ |
present or absent, never two |
| 0..* | std::vector<OrderLine> lines_ |
any number; a lower bound such as 1..* needs a rule in code |
The type carries as much of the multiplicity as it can. The rule “one or more
lines once placed” does not fit in a type, so place() checks it and the
outline’s note records it.
Read the sketch’s arrow to Customer from both sides: one order has exactly
one customer; one customer has zero or more orders. The Customer class has no
member for its orders. Finding all orders for a customer is a separate
question, usually answered by the order store, with a lookup by customer ID.
Testing multiplicity and lifecycle
Section titled “Testing multiplicity and lifecycle”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure if// the condition is false. LLD_CHECK_EQ(actual, expected) records a failure// unless the two are equal, and prints both. LLD_CHECK_THROWS(expression,// type) fails unless the expression throws that type of exception. They come// from the site's small test header, lld_test.hpp.
// namespace { ... } with no name keeps the helper private to this file.namespace {
// A draft order with one line: 1 of item "A" at 100 cents. Returned by// value, so each test gets its own order.Order draft_with_one_line() { Order order{CustomerId{1}}; order.add_line("A", 1, 100); return order;}
} // namespace
// "A" added again (2 more) does not make a second line: one line, quantity 3.LLD_TEST(adding_the_same_item_merges_lines) { Order order = draft_with_one_line(); order.add_line("A", 2, 100); LLD_CHECK_EQ(order.lines().size(), std::size_t{1}); LLD_CHECK_EQ(order.lines().front().quantity, 3);}
// The lower bound of 1..* is enforced at place(): with no lines it throws,// and the order is still a draft.LLD_TEST(an_empty_order_cannot_be_placed) { Order order{CustomerId{1}}; LLD_CHECK_THROWS(order.place(), std::logic_error); LLD_CHECK(order.state() == OrderState::draft); // unchanged}
// remove_line returns true when it removed something and false the second// time. A draft may then be empty, but cannot be placed.LLD_TEST(removing_the_last_line_is_allowed_while_draft) { Order order = draft_with_one_line(); LLD_CHECK(order.remove_line("A")); LLD_CHECK(!order.remove_line("A")); LLD_CHECK(order.lines().empty()); // 0 lines is fine for a draft... LLD_CHECK_THROWS(order.place(), std::logic_error); // ...but not for placing}
// After place(), every change to lines or coupon throws std::logic_error,// and the checks after them prove nothing changed: still one line, no// coupon (`!order.coupon()` is true for an empty optional), still placed.LLD_TEST(a_placed_order_cannot_change) { Order order = draft_with_one_line(); order.place(); LLD_CHECK_THROWS(order.add_line("B", 1, 100), std::logic_error); LLD_CHECK_THROWS(order.remove_line("A"), std::logic_error); LLD_CHECK_THROWS(order.apply_coupon({"X", 5}), std::logic_error); LLD_CHECK_EQ(order.lines().size(), std::size_t{1}); LLD_CHECK(!order.coupon()); LLD_CHECK(order.state() == OrderState::placed);}
// No tracking number as a draft or when placed; "T-1" once shipped. A second// ship() is refused and does not overwrite the tracking number.LLD_TEST(tracking_exists_exactly_when_shipped) { Order order = draft_with_one_line(); LLD_CHECK(!order.tracking()); order.place(); LLD_CHECK(!order.tracking()); order.ship("T-1"); LLD_CHECK_EQ(*order.tracking(), std::string{"T-1"}); LLD_CHECK_THROWS(order.ship("T-2"), std::logic_error); LLD_CHECK_EQ(*order.tracking(), std::string{"T-1"});}
// Three separate orders, one per starting state: a draft and a placed order// can be cancelled (and cancelling again is refused); a shipped one cannot,// and stays shipped.LLD_TEST(cancel_is_allowed_only_before_shipping) { Order draft = draft_with_one_line(); draft.cancel(); LLD_CHECK(draft.state() == OrderState::cancelled);
Order placed = draft_with_one_line(); placed.place(); placed.cancel(); LLD_CHECK(placed.state() == OrderState::cancelled); LLD_CHECK_THROWS(placed.cancel(), std::logic_error); // already cancelled
Order shipped = draft_with_one_line(); shipped.place(); shipped.ship("T-1"); LLD_CHECK_THROWS(shipped.cancel(), std::logic_error); LLD_CHECK(shipped.state() == OrderState::shipped);}
// 0..1 coupons: the second replaces the first, so the total is 100 less 10%// = 90 cents, not 50% off. A bad coupon (0%) throws and leaves "SECOND" in// place.LLD_TEST(a_second_coupon_replaces_the_first) { Order order = draft_with_one_line(); order.apply_coupon({"FIRST", 50}); order.apply_coupon({"SECOND", 10}); LLD_CHECK_EQ(order.coupon()->code, std::string{"SECOND"}); LLD_CHECK_EQ(order.total_cents(), std::int64_t{90}); LLD_CHECK_THROWS(order.apply_coupon({"BAD", 0}), std::invalid_argument); LLD_CHECK_EQ(order.coupon()->code, std::string{"SECOND"});}Two kinds of test matter here:
- Each multiplicity rule, at its edges. Zero lines (allowed while draft, refused when placing), one line, the same item twice (still one line), a second coupon (still one coupon).
- Each transition, allowed and refused. Each transition from draft and
placed, the changes a placed order refuses, and the final states refusing
cancelandship. A refused call must leave the order unchanged, so the tests check the state or data after the refusals.
Other designs
Section titled “Other designs”One class per state. Instead of one Order with a state field, there could
be DraftOrder, PlacedOrder, and ShippedOrder, where place() on a draft
returns a new PlacedOrder. Then a placed order has no add_line function at
all, and calling one in the wrong state does not compile. That is attractive
when the states have very different data and operations. It is awkward when the
states share most of their data, or when orders of every state must be stored
together, as an order store would. This page uses one class because every state
has the same data.
A std::variant of states. The order could hold
std::variant<Draft, Placed, Shipped, Cancelled>, where Shipped holds the
tracking number. Then “tracking number present exactly when shipped” is true by
construction. It costs more code to read and change the data in each state. The
state pattern lesson returns to these choices.
A non-empty container type. A small class that holds a first element plus a
std::vector of the rest can never be empty, so 1..* is enforced by the type.
Here it would not help: a draft may be empty, and the rule starts only when the
order is placed.
Common mistakes
Section titled “Common mistakes”0..1written as a plain member with a magic value, such as an empty string for “no tracking number yet”. Readers cannot see that the value may be missing.1written as a nullable pointer. Every reader then asks “can this be null?”, and some will forget to check.- A
1..*rule that only the constructor checks. A laterremove_lineempties the container. Every function that removes elements must keep the rule. - A state field that any code can set, such as a public
statemember or aset_statefunction. Then a shipped order can become a draft, and every state-dependent rule is broken. - Lifecycle rules scattered across the callers, as checks of the form
if (order.state() == …)before each call. The order should refuse; callers may ask first.
When a requirement changes
Section titled “When a requirement changes”New requirement: “An order may be split into several shipments, each with its own tracking number. It is shipped when every line has been sent.”
The tracking number’s multiplicity changes from 0..1 to 0..*, and it moves:
a tracking number now belongs to a shipment, not to the order. So
std::optional<std::string> tracking_ becomes
std::vector<Shipment> shipments_, where each Shipment holds a tracking
number and the lines it contains. The lifecycle gains a state, partly shipped,
between placed and shipped. And a new rule appears: a line belongs to at most
one shipment. Drawing the state diagram again, before changing the code, shows
the new questions: can a partly shipped order be cancelled? Can its unshipped
lines?
Exercise: Derive member types from multiplicities
A library’s model has these facts. For each one, write the member (type and name) in the class it belongs to, and say whether a rule beyond the type is needed.
- A loan is for exactly one copy, and one member.
- A member may have one default branch for collecting holds, or none.
- A title has one or more authors, in the order printed on the cover.
- A branch has many copies. Copies are looked up by barcode.
- A hold is for one title. When a copy is kept for it, the hold records which copy; before that, no copy.
- A member may list at most 3 favourite branches.
Show the explained answer
- In
Loan:CopyId copy_;andMemberId member_;, both set by the constructor, with no setters. IDs, because loans are stored long after the objects in memory are gone. No extra rule. - In
Member:std::optional<BranchId> default_branch_;. The type says “zero or one”. No extra rule. - In
Title:std::vector<AuthorName> authors_;, a vector because order matters. Rule: never empty. Enforce it in the constructor (take the authors as an argument and refuse an empty list) and in any function that removes an author. - In
Branch, if the branch owns the copies:std::unordered_map<Barcode, Copy> copies_;(orstd::mapif they must be listed in barcode order). The key gives lookup by barcode. If copies are owned elsewhere,std::unordered_set<Barcode>. Either way,Barcodeneeds astd::hashspecialization, as in the identity lesson. - In
Hold:TitleId title_;andstd::optional<CopyId> kept_copy_;. As with the order’s tracking number, the optional’s presence follows the hold’s lifecycle (waiting, then kept). Rule: a copy is set exactly when the hold is kept, and the copy is of this title. - In
Member:std::vector<BranchId> favourite_branches_;. Rules: at most 3, and no branch twice.std::array<BranchId, 3>is not a good fit: it always holds exactly 3. A container plus a check inadd_favouriteis simpler.
Summary
Section titled “Summary”- Multiplicity says how many objects take part at each end of a relationship:
1,0..1,0..*,1..*. 1is a plain member or ID set by the constructor;0..1isstd::optionalor a nullable pointer;0..*is a container;1..*is a container plus a rule the class must keep.- Multiplicity can depend on the state: describe the lifecycle, and tie each rule to the states where it holds.
- For each class, decide who creates it, who owns it, who destroys it, and what happens to the objects that refer to it.