The before code mixes order types and payment logic, duplicating code and making changes risky. The after code uses the Strategy pattern to separate payment methods, making it easier to add new payment types without changing order processing.
### Before: Spaghetti code with duplicated logic and tight coupling
class OrderProcessor:
def process(self, order):
if order.type == 'online':
print(f"Processing online order {order.id}")
# duplicated payment logic
if order.payment_method == 'card':
print("Charging card")
elif order.payment_method == 'paypal':
print("Charging PayPal")
elif order.type == 'store':
print(f"Processing store order {order.id}")
# duplicated payment logic
if order.payment_method == 'card':
print("Charging card")
elif order.payment_method == 'paypal':
print("Charging PayPal")
### After: Applying Strategy pattern to separate payment logic
class PaymentStrategy:
def pay(self, order):
pass
class CardPayment(PaymentStrategy):
def pay(self, order):
print("Charging card")
class PaypalPayment(PaymentStrategy):
def pay(self, order):
print("Charging PayPal")
class OrderProcessor:
def __init__(self, payment_strategy: PaymentStrategy):
self.payment_strategy = payment_strategy
def process(self, order):
print(f"Processing {order.type} order {order.id}")
self.payment_strategy.pay(order)
# Usage
order = type('Order', (), {'id': 123, 'type': 'online', 'payment_method': 'card'})()
processor = OrderProcessor(CardPayment())
processor.process(order)