Facades often expose a few extra-simple shortcuts for the most common request. Most customers buy a single unit, so add quick_buy(item, amount) that fills in a quantity of 1 and delegates to place_order.
The key idea: quick_buy adds no new logic and touches no subsystem directly. It simply calls self.place_order(item, 1, amount) and returns whatever place_order returns. Because it goes through the same method, it automatically inherits reservation, payment rollback, shipping, and the order log, and it shares the exact same subsystem instances and state.
class Inventory:
def __init__(self, stock):
self.stock = dict(stock)
def reserve(self, item, qty):
if self.stock.get(item, 0) >= qty:
self.stock[item] -= qty
return True
return False
def release(self, item, qty):
self.stock[item] = self.stock.get(item, 0) + qty
class Payment:
def __init__(self, balance):
self.balance = balance
def charge(self, amount):
if amount <= self.balance:
self.balance -= amount
return True
return False
class Shipping:
def schedule(self, item):
return "trk-" + item
class CheckoutFacade:
def __init__(self, inventory, payment, shipping):
self.inventory = inventory
self.payment = payment
self.shipping = shipping
self.orders = []
def place_order(self, item, qty, amount):
if not self.inventory.reserve(item, qty):
return {"ok": False, "reason": "out_of_stock"}
if not self.payment.charge(amount):
self.inventory.release(item, qty)
return {"ok": False, "reason": "payment_declined"}
tracking = self.shipping.schedule(item)
self.orders.append(
{"item": item, "qty": qty, "amount": amount, "tracking": tracking}
)
return {"ok": True, "tracking": tracking}
def quick_buy(self, item, amount):
"""Buy a single unit (qty=1) of item via place_order."""
# TODO: call self.place_order with qty defaulting to 1 and return
# its result.
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Facades often expose a few extra-simple shortcuts for the most common request. Most customers buy a single unit, so add quick_buy(item, amount) that fills in a quantity of 1 and delegates to place_order.
The key idea: quick_buy adds no new logic and touches no subsystem directly. It simply calls self.place_order(item, 1, amount) and returns whatever place_order returns. Because it goes through the same method, it automatically inherits reservation, payment rollback, shipping, and the order log, and it shares the exact same subsystem instances and state.
Press Run Tests or ββ© to check your solution.