Facebook Pixel

Exercise: Association, Aggregation & Composition

This exercise puts the association, aggregation, and composition lesson into code. You will build an order system where a catalog aggregates products that exist independently, while orders are composed of line items that only exist within a single order.

Scenario

An order system has two top-level objects: a Catalog and a collection of Order instances. The Catalog aggregates Product objects — products exist independently of any order and can be referenced by multiple orders. Each Order is composed of LineItem objects: a line item is created by the order, belongs exclusively to it, and holds a reference to a catalog product plus a quantity. Each command produces exactly one output line.

Commands

CommandBehaviorOutput
["product", sku, price]Register a product in the catalog"Catalogued <sku>"
["additem", order_id, sku, qty]Add a line item to the order referencing the catalog product. Orders are created on first use."Added <qty> <sku> to <order_id>", or "Unknown sku <sku>" if the sku is not in the catalog
["total", order_id]Report the sum of price * qty across all line items"<order_id> total: <sum>" (0 for an order with no items)

price and qty are integers.

Example
Input
7
product WIDGET 10
product GADGET 25
additem order1 WIDGET 3
additem order1 GADGET 2
additem order2 UNKNOWN 1
total order1
total order2
Output
Catalogued WIDGET
Catalogued GADGET
Added 3 WIDGET to order1
Added 2 GADGET to order1
Unknown sku UNKNOWN
order1 total: 80
order2 total: 0
Explanation
Two products are registered. Three WIDGET at 10 each and two GADGET at 25 each are added to order1, giving a total of 30 + 50 = 80. The attempt to add an UNKNOWN sku to order2 is rejected; because no items were successfully added, order2's total is 0.

Your task

Fill in LineItem.subtotal(), Order.add_item(), Order.total(), Catalog.add(), and Catalog.get() so 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