能举个重构的例子吗
当然可以。假设你有一个函数,叫做"计算订单总价",它现在只支持一种商品和一种折扣。
def calculate_total(price, quantity, discount):
return price * quantity * (1 - discount)
一开始没问题,但后来加了会员折扣、满减、运费等,代码变成了这样:
def calculate_total(price, quantity, discount, member_discount, free_shipping_threshold, shipping_fee):
total = price * quantity * (1 - discount)
if total > 100: # 满100减20
total -= 20
total = total * (1 - member_discount)
if total < free_shipping_threshold:
total += shipping_fee
return total
这个函数现在参数很多,逻辑混杂,很难看懂和修改。
重构的思路:把不同计算逻辑拆成独立的小函数,并让主函数只负责组合它们。
重构后:
def calculate_subtotal(price, quantity):
return price * quantity
def apply_coupon_discount(amount, discount):
return amount * (1 - discount)
def apply_full_reduction(amount):
if amount > 100:
return amount - 20
return amount
def apply_member_discount(amount, member_discount):
return amount * (1 - member_discount)
def add_shipping(amount, free_shipping_threshold, shipping_fee):
if amount < free_shipping_threshold:
return amount + shipping_fee
return amount
def calculate_total(price, quantity, discount, member_discount, free_shipping_threshold, shipping_fee):
subtotal = calculate_subtotal(price, quantity)
after_coupon = apply_coupon_discount(subtotal, discount)
after_reduction = apply_full_reduction(after_coupon)
after_member = apply_member_discount(after_reduction, member_discount)
total = add_shipping(after_member, free_shipping_threshold, shipping_fee)
return total
这样,每个小函数只做一件事,名字也说明了它做什么。如果以后修改折扣规则,只需改apply_coupon_discount,不会影响其他逻辑。这就是一个典型的例子:提取函数的重构。