KatInterview

Design a Shopping Cart with OOP: Catalog, Lines, and Totals

Data Structure DesignModel answer
MediumModel answerData Structure Designobject-oriented designpythonmoney arithmetic

Last 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:

SituationWhat should happen?
add called for a product already in the cartMerge quantities, replace, or reject?
Quantity set to zero via updateRemove the line silently, or raise an error?
Unknown product IDRaise, return None, or ignore?
Negative or non-integer quantityRaise, clamp, or ignore?
Price volatilityIs price locked when the item is added, or re-read from the catalog when the total is computed?
Inventory checkOn 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.