The before code mixes product storage, cart management, and checkout in one class, making it hard to maintain. The after code separates these concerns into Product, Cart, and Order classes, each with clear responsibilities and interactions.
### Before: All logic in one class (bad design)
class ECommerce:
def __init__(self):
self.products = {}
self.cart = {}
def add_product(self, product_id, name, price):
self.products[product_id] = {'name': name, 'price': price}
def add_to_cart(self, product_id, quantity):
if product_id in self.products:
self.cart[product_id] = self.cart.get(product_id, 0) + quantity
def checkout(self):
total = 0
for pid, qty in self.cart.items():
total += self.products[pid]['price'] * qty
self.cart.clear()
return total
### After: Separate Product, Cart, and Order classes (good design)
class Product:
def __init__(self, product_id: int, name: str, price: float):
self.product_id = product_id
self.name = name
self.price = price
class Cart:
def __init__(self):
self.items = {} # product_id -> quantity
def add_product(self, product: Product, quantity: int):
self.items[product.product_id] = self.items.get(product.product_id, 0) + quantity
def get_total(self, product_catalog: dict) -> float:
total = 0
for pid, qty in self.items.items():
total += product_catalog[pid].price * qty
return total
def clear(self):
self.items.clear()
class Order:
def __init__(self, cart: Cart, product_catalog: dict):
self.cart = cart
self.product_catalog = product_catalog
self.total_amount = 0
self.is_paid = False
def place_order(self):
self.total_amount = self.cart.get_total(self.product_catalog)
self.is_paid = True # Simplified
self.cart.clear()
return self.total_amount