一、背景
在软件开发过程中,业务逻辑BUG是常见的之一。这类BUG往往出代码的复杂逻辑处理中,可能导致程序运行不正常,影响用户体验。是一个业务逻辑BUG的面试题,让我们一起来分析和解决它。
二、面试题
假设有一个在线购物系统,用户可以在系统中查看商品信息、添加商品到购物车、结算支付等功能。系统中的商品价格是动态计算的,根据不同的促销活动,商品价格会有所调整。是一个业务逻辑的处理,请找出的BUG,并给出解决方案。
python
class Product:
def __init__(self, price):
self.price = price
class ShoppingCart:
def __init__(self):
self.products = []
def add_product(self, product):
self.products.append(product)
def calculate_total_price(self):
total_price = 0
for product in self.products:
if product.price > 100:
total_price += product.price * 0.9 # 促销活动:商品价格超过100元,打9折
else:
total_price += product.price
return total_price
# 示例使用
cart = ShoppingCart()
cart.add_product(Product(120))
cart.add_product(Product(80))
total = cart.calculate_total_price()
print(f"Total Price: {total}")
三、BUG分析
在这个例子中,我们注意到一个BUG:当商品价格为120元时,根据促销活动应该打9折,但实际计算时并没有正确应用折扣。出在`calculate_total_price`方法中,对于商品价格的判断条件是`product.price > 100`,而应该判断的是`product.price >= 100`,因为当商品价格正好是100元时,也应该享受9折优惠。
四、解决方案
为了解决这个BUG,我们需要修改`calculate_total_price`方法中的判断条件,确保所有价格超过或等于100元的商品都应用9折优惠。是修改后的代码:
python
class ShoppingCart:
def __init__(self):
self.products = []
def add_product(self, product):
self.products.append(product)
def calculate_total_price(self):
total_price = 0
for product in self.products:
if product.price >= 100:
total_price += product.price * 0.9 # 促销活动:商品价格超过或等于100元,打9折
else:
total_price += product.price
return total_price
# 示例使用
cart = ShoppingCart()
cart.add_product(Product(120))
cart.add_product(Product(80))
cart.add_product(Product(100)) # 添加一个价格为100元的商品
total = cart.calculate_total_price()
print(f"Total Price: {total}")
通过上述修改,系统将正确地应用促销活动,对所有价格超过或等于100元的商品进行9折优惠。
五、
在解决业务逻辑BUG时,我们需要仔细审查代码中的逻辑判断条件,确保它们符合业务需求。在这个例子中,通过简单的修改,我们解决了因判断条件错误导致的BUG。这类在计算机专业面试中很常见,它考察了者对业务逻辑的理解和解决能力。
还没有评论呢,快来抢沙发~