Design Shopping Cart (Basket)

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2022-05-27

Problem Statement

Design a Shopping Cart (Basket) system for an e-commerce platform. The cart should allow users to add, update, and remove products, calculate totals, and handle promotions or discounts. The focus is on object-oriented design, modularity, and maintainability.


Functional Requirements


1.Add Item
•Users can add a product to the cart with a specified quantity.
•If the product already exists in the cart, increment the quantity.
2.Remove Item
•Users can remove a product from the cart.
3.Update Quantity
•Users can update the quantity of a specific product.
4.View Cart
•Display all products in the cart with details: product name, price, quantity, subtotal.
•Calculate the total amount, including taxes and discounts.
5.Apply Discounts / Promotions
•Support percentage discounts, fixed amount discounts, or promo codes.
•Update total dynamically after applying promotions.
6.Checkout Preparation
•Prepare an order summary ready for checkout.
•Optionally validate stock availability.


Non-Functional Requirements


•Extensibility: Easy to add new pricing rules, promotions, or product types.
•Consistency: Ensure quantities and totals are correctly calculated.
•Thread Safety: Handle concurrent updates to the cart (multi-device scenarios).
•Performance: Operations should be efficient for carts with many items.


Edge Cases & Constraints


•Adding a product with zero or negative quantity → ignore or throw error.
•Removing a product not in the cart → ignore or throw error.
•Applying expired or invalid promo codes → reject with proper error.
•Handling fractional prices, taxes, or currency conversions.


Design Hints


•Key Classes / Interfaces:
•Cart → represents the user’s shopping cart; contains CartItem list.
•CartItem → represents a product and quantity.
•Product → contains product ID, name, price, and other metadata.
•Discount / Promotion → abstract class or interface for different discount types.
•PricingService → calculates total, taxes, and applies discounts.
•CartService → main API to add/update/remove items and get cart summary.
•Design Patterns:
•Strategy Pattern → for different discount or promotion strategies.
•Observer Pattern (Optional) → notify UI or other services when cart updates.


Example Flow


1.User adds 2 units of "Laptop" → CartItem added.
2.User adds 1 unit of "Mouse" → new CartItem added.
3.User updates "Laptop" quantity to 3 → CartItem quantity updated.
4.User applies promo code "DISCOUNT10" → PricingService recalculates total.
5.User views cart → see all items, subtotal, discounts, and final total.


Evaluation Areas


•Clean class design and separation of concerns.
•Handling edge cases and promotions correctly.
•Proper use of OOP principles and design patterns.
•Thread safety and consistency in multi-device/cart updates.


Solution

Comments