Facebook Pixel

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

CommandBehaviorOutput lines
["stock", item, qty]Set inventory for that item"Stocked <qty> <item>" (1 line)
["order", item, qty]Execute the ordering sequenceAlways emits lines 1–2; emits lines 3–4 on success or line 3 (rejected) on failure

For ["order", item, qty], always emit:

  1. "OrderService -> Inventory: check <item>"
  2. "Inventory -> OrderService: <available> available" (where <available> is current stock, or 0 if 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.

Example
Input
6
stock apples 5
order apples 3
order apples 3
order apples 2
stock bananas 1
order bananas 2
Output
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
Explanation
5 apples are stocked. The first order of 3 succeeds, leaving 2 in stock. The second order of 3 is rejected because only 2 are available. The third order of 2 succeeds, emptying the stock. One banana is stocked, but the order for 2 bananas is rejected because only 1 is available.

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.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro