Design a Shopping Cart with OOP: Catalog, Lines, and Totals
Data Structure DesignModel answerLast updated
Model a shopping cart in object-oriented code: add, update, and remove items, compute an exact total, and handle edge cases consistently.
Shopping Cart Object Model
You are building the core domain layer for a small e-commerce app. Design and implement a shopping cart in object-oriented code using any language you like. The goal is a clean, runnable model — not a distributed system or a database schema.
What the cart must support
- Add an item — given a product ID and a quantity, place it in the cart.
- Update quantity — change how many units of an existing product are in the cart.
- Remove an item — take a product out of the cart entirely.
- List contents — return the current line items (product info + quantity).
- Compute total — return the exact price for everything in the cart.
Products live in a catalog that the cart can query by product ID. Every product has at least an ID, a human-readable name, and a unit price.
Implement the classes, wire them together, and include a short usage example or a set of tests that exercise both the normal flow and the edge cases below.
Constraints
- Single shopper, single process. Persistence, authentication, checkout, and payment are all out of scope unless you are asked to extend the design.
- Money must be computed exactly. Explain your representation choice.
Edge cases to address explicitly
Before writing a line of code, decide — and state — your policy for each of these:
| Situation | What should happen? |
|---|---|
add called for a product already in the cart | Merge quantities, replace, or reject? |
Quantity set to zero via update | Remove the line silently, or raise an error? |
| Unknown product ID | Raise, return None, or ignore? |
| Negative or non-integer quantity | Raise, clamp, or ignore? |
| Price volatility | Is price locked when the item is added, or re-read from the catalog when the total is computed? |
| Inventory check | On add, or deferred to checkout? |
There are no universally correct answers — but your choices must be consistent and you must be able to justify them.
Hints
Hint 1
Separate three responsibilities: the Product (data), the CartLine (one product + its quantity), and the Cart (the collection). The Cart delegates catalog lookups rather than owning catalog logic itself.
Hint 2
For exact money arithmetic, avoid float entirely. Use Python's `Decimal` with a fixed precision, Java's `BigDecimal`, or store prices as integer cents and convert only when displaying. State your choice up front.
Hint 3
An `OrderedDict` (or a regular dict in Python 3.7+) keyed by product ID gives O(1) lookup for updates and removals while keeping insertion order for deterministic listing — cleaner than a plain list.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The design splits into three thin classes with clear ownership, one explicit edge-case policy table, and a money representation that never touches float.
Class responsibilities
Product — pure data: ID, name, unit price. Immutable after construction.
CartLine — pairs a Product with a mutable quantity. Owns the per-line subtotal calculation.
Catalog — a registry of products. The cart depends on it for lookups but does not own it.
ShoppingCart — the collection of CartLine objects, indexed by product ID. Owns all mutation and the total calculation. Can accept an optional PricingStrategy for discounts or tax (see extension notes below).
Explicit edge-case policy
| Situation | Policy chosen |
|---|---|
add for a product already in the cart | Merge: quantities are summed. This matches user expectation ("add two more"). |
update to zero | Remove the line silently. Zero units means the item is gone. |
update to a negative value | Raise ValueError. Negative quantity has no business meaning. |
| Unknown product ID | Raise KeyError. Silently ignoring it hides bugs. |
| Non-integer quantity | Raise TypeError. The domain sells discrete units. |
| Price volatility | Read from catalog at total-time, not locked on add. Simpler, and consistent with most retail carts. |
| Inventory | Deferred to checkout. Out of scope here. |
State these policies before writing code in an interview. The interviewer wants to see that you think about the boundaries, not just the happy path.
Money representation
float is disqualified: 0.1 + 0.2 == 0.30000000000000004 in Python. Two safe options:
- Integer cents: store prices as
int(e.g.1099for $10.99), convert to a decimal string only for display. Zero external dependencies. decimal.Decimalwith fixed precision: more readable arithmetic, slightly more ceremony.
The implementation below uses integer cents to keep the code dependency-free.
Implementation (Python)
from __future__ import annotations
from collections import OrderedDict
from typing import Iterator
class Product:
"""Immutable product record. price_cents is a non-negative integer."""
def __init__(self, product_id: str, name: str, price_cents: int) -> None:
if price_cents < 0:
raise ValueError(f"price_cents must be >= 0, got {price_cents}")
self.product_id = product_id
self.name = name
self.price_cents = price_cents # e.g. 1099 represents $10.99
def __repr__(self) -> str:
return f"Product({self.product_id!r}, {self.name!r}, ${self.price_cents/100:.2f})"
class CartLine:
"""One product and its quantity in the cart."""
def __init__(self, product: Product, quantity: int) -> None:
self.product = product
self.quantity = quantity # always a positive int when in the cart
@property
def subtotal_cents(self) -> int:
return self.product.price_cents * self.quantity
def __repr__(self) -> str:
return (
f"CartLine({self.product.name!r} x{self.quantity} "
f"= ${self.subtotal_cents/100:.2f})"
)
class Catalog:
def __init__(self, products: list[Product]) -> None:
self._store: dict[str, Product] = {p.product_id: p for p in products}
def get(self, product_id: str) -> Product:
if product_id not in self._store:
raise KeyError(f"Unknown product ID: {product_id!r}")
return self._store[product_id]
class ShoppingCart:
def __init__(self, catalog: Catalog) -> None:
self._catalog = catalog
# OrderedDict preserves insertion order for predictable listing
self._lines: OrderedDict[str, CartLine] = OrderedDict()
def add(self, product_id: str, quantity: int) -> None:
"""Add units of a product. Merges if already present."""
self._validate_quantity(quantity)
product = self._catalog.get(product_id) # raises KeyError if unknown
if product_id in self._lines:
self._lines[product_id].quantity += quantity
else:
self._lines[product_id] = CartLine(product, quantity)
def update(self, product_id: str, quantity: int) -> None:
"""Set the quantity of an existing line. Quantity 0 removes the line."""
if not isinstance(quantity, int):
raise TypeError(f"quantity must be int, got {type(quantity).__name__}")
if quantity < 0:
raise ValueError(f"quantity must be >= 0, got {quantity}")
if product_id not in self._lines:
raise KeyError(f"Product {product_id!r} is not in the cart")
if quantity == 0:
del self._lines[product_id]
else:
self._lines[product_id].quantity = quantity
def remove(self, product_id: str) -> None:
"""Remove a product from the cart entirely."""
if product_id not in self._lines:
raise KeyError(f"Product {product_id!r} is not in the cart")
del self._lines[product_id]
def items(self) -> Iterator[CartLine]:
return iter(self._lines.values())
def total_cents(self) -> int:
"""Re-reads current catalog prices; returns total in cents."""
total = 0
for line in self._lines.values():
# Re-fetch price in case catalog was updated
current_product = self._catalog.get(line.product.product_id)
total += current_product.price_cents * line.quantity
return total
def total_display(self) -> str:
return f"${self.total_cents()/100:.2f}"
@staticmethod
def _validate_quantity(quantity: int) -> None:
if not isinstance(quantity, int):
raise TypeError(f"quantity must be int, got {type(quantity).__name__}")
if quantity <= 0:
raise ValueError(f"quantity must be > 0, got {quantity}")
# --- Usage example ---
if __name__ == "__main__":
catalog = Catalog([
Product("SKU-1", "Wireless Mouse", 2999), # $29.99
Product("SKU-2", "USB-C Hub", 4999), # $49.99
Product("SKU-3", "Desk Mat", 1500), # $15.00
])
cart = ShoppingCart(catalog)
cart.add("SKU-1", 1)
cart.add("SKU-2", 2)
cart.add("SKU-1", 1) # merge: SKU-1 is now qty 2
print("Cart contents:")
for line in cart.items():
print(" ", line)
print("Total:", cart.total_display()) # $159.96
cart.update("SKU-2", 1)
print("After update SKU-2 to 1:", cart.total_display()) # $109.97
cart.update("SKU-1", 0) # removes the line
print("After zeroing SKU-1:", cart.total_display()) # $49.99
Complexity
| Operation | Time | Space |
|---|---|---|
add / update / remove | O(1) | — |
total_cents | O(n) in cart size | O(1) extra |
items | O(n) | O(1) extra |
Extension seam for discounts and tax
To add pricing rules without rewriting the cart, inject a PricingStrategy:
class PricingStrategy:
def apply(self, lines: list[CartLine]) -> int:
return sum(l.subtotal_cents for l in lines)
Subclasses override apply — a percentage discount, a buy-two-get-one rule, or tax all fit in without touching ShoppingCart.
Common mistakes to avoid
- Using
floatfor prices — rounding errors compound at scale and in tests. - Storing price only on
CartLinewith no path back to the catalog — makes price-update handling messy. - No policy for duplicate
add— interviewers will probe this immediately. - Forgetting the zero-quantity edge case on
update. - One giant
Cartclass with catalog logic embedded — hard to test in isolation.