The before code processes refunds without any rules, always refunding full amount if cancelled. The after code introduces a CancellationPolicy class that calculates refunds based on timing, allowing full refunds within 24 hours and partial refunds afterward. This enforces business rules consistently.
### Before: No policy enforcement, refunds processed directly
class Order:
def __init__(self, amount):
self.amount = amount
self.is_cancelled = False
def cancel(self):
self.is_cancelled = True
def refund(self):
if self.is_cancelled:
return self.amount # Full refund without checks
return 0
### After: Policy enforced with timing and partial refund rules
from datetime import datetime, timedelta
class CancellationPolicy:
def __init__(self, full_refund_period_hours, partial_refund_percent):
self.full_refund_period = timedelta(hours=full_refund_period_hours)
self.partial_refund_percent = partial_refund_percent
def calculate_refund(self, order_time, cancel_time, amount):
if cancel_time - order_time <= self.full_refund_period:
return amount # Full refund
else:
return amount * self.partial_refund_percent / 100 # Partial refund
class OrderWithPolicy:
def __init__(self, amount, order_time):
self.amount = amount
self.order_time = order_time
self.is_cancelled = False
self.cancel_time = None
self.policy = CancellationPolicy(full_refund_period_hours=24, partial_refund_percent=50)
def cancel(self, cancel_time):
self.is_cancelled = True
self.cancel_time = cancel_time
def refund(self):
if not self.is_cancelled:
return 0
return self.policy.calculate_refund(self.order_time, self.cancel_time, self.amount)