Exercise: Sequence Diagrams
This exercise puts the sequence diagrams lesson into code.
Scenario
The sequence diagram below shows the happy path for placing an order. OrderService coordinates two collaborators — Inventory and Payment — in the exact order the arrows show.
Implement an OrderService that holds an Inventory and a Payment as separate collaborator objects. The function run_order accepts a list of commands and returns the messages each command emits, flattened in order.
Commands
| Command | Behavior | Output lines |
|---|---|---|
["stock", item, qty] | Set inventory for that item | "Stocked <qty> <item>" (1 line) |
["order", item, qty] | Execute the ordering sequence | Always emits lines 1–2; emits lines 3–4 on success or line 3 (rejected) on failure |
For ["order", item, qty], always emit:
"OrderService -> Inventory: check <item>""Inventory -> OrderService: <available> available"(where<available>is current stock, or0if never stocked)
If available quantity is at least qty, decrement stock, then emit:
3. "OrderService -> Payment: charge"
4. "OrderService -> Customer: confirmed"
Otherwise emit:
3. "OrderService -> Customer: rejected"
All quantities are integers.
6 stock apples 5 order apples 3 order apples 3 order apples 2 stock bananas 1 order bananas 2
Stocked 5 apples OrderService -> Inventory: check apples Inventory -> OrderService: 5 available OrderService -> Payment: charge OrderService -> Customer: confirmed OrderService -> Inventory: check apples Inventory -> OrderService: 2 available OrderService -> Customer: rejected OrderService -> Inventory: check apples Inventory -> OrderService: 2 available OrderService -> Payment: charge OrderService -> Customer: confirmed Stocked 1 bananas OrderService -> Inventory: check bananas Inventory -> OrderService: 1 available OrderService -> Customer: rejected
Your task
Fill in Inventory.check, Inventory.deduct, Inventory.stock, and the stock and order methods on OrderService so that the commands produce the output above.