Practical Exercise 6
Hands-On
Use AI to safely refactor and modernize existing code
2026 WayUp
1
Write characterization tests before refactoring
2
Extract methods and reduce complexity
3
Apply design patterns with AI guidance
4
Maintain functionality while improving code
def process_order(data):
result = {}
if data:
if 'items' in data:
if len(data['items']) > 0:
t = 0
for i in data['items']:
if 'price' in i and 'qty' in i:
if i['qty'] > 0:
if i['price'] > 0:
t = t + (i['price'] * i['qty'])
if i.get('taxable', True):
t = t + (i['price'] * i['qty'] * 0.08)
result['subtotal'] = t
if 'coupon' in data:
if data['coupon'] == 'SAVE10':
t = t * 0.9
if data['coupon'] == 'SAVE20':
t = t * 0.8
result['total'] = t
result['status'] = 'ok'
else:
result['status'] = 'error'
result['msg'] = 'no items'
else:
result['status'] = 'error'
result['msg'] = 'invalid'
else:
result['status'] = 'error'
result['msg'] = 'no data'
return result
validate_order_data()calculate_item_total()calculate_tax()apply_coupon()build_success_result()build_error_result()"Extract the tax calculation logic into a separate function called calculate_tax. Keep tests passing."
# Before (nested)
def process(data):
if data:
if 'items' in data:
if len(data['items']) > 0:
# do work
else:
return error
else:
return error
else:
return error
# After (guard clauses)
def process(data):
if not data:
return error
if 'items' not in data:
return error
if len(data['items']) == 0:
return error
# do work (flat)
from abc import ABC, abstractmethod
class DiscountStrategy(ABC):
@abstractmethod
def apply(self, total: float) -> float:
pass
class NoDiscount(DiscountStrategy):
def apply(self, total: float) -> float:
return total
class PercentDiscount(DiscountStrategy):
def __init__(self, percent: int):
self.percent = percent
def apply(self, total: float) -> float:
return total * (1 - self.percent / 100)
# Usage
DISCOUNTS = {
'SAVE10': PercentDiscount(10),
'SAVE20': PercentDiscount(20),
}
def apply_discount(total: float, coupon: str) -> float:
strategy = DISCOUNTS.get(coupon, NoDiscount())
return strategy.apply(total)
from dataclasses import dataclass
from typing import List, Optional
@dataclass
class OrderItem:
price: float
quantity: int
taxable: bool = True
def process_order(data: Optional[dict]) -> dict:
error = validate_order_data(data)
if error:
return build_error_result(error)
items = [OrderItem(**item) for item in data['items']]
subtotal = calculate_subtotal(items)
total = apply_discount(subtotal, data.get('coupon'))
return build_success_result(subtotal, total)
def validate_order_data(data: Optional[dict]) -> Optional[str]:
if not data:
return 'no data'
if 'items' not in data:
return 'invalid'
if not data['items']:
return 'no items'
return None
You've safely modernized legacy code
Next: Practical 7 - API Integration with AI
2026 WayUp - way-up.io