背景
在软件开发过程中,业务逻辑BUG是常见的之一。这类BUG往往与业务规则、数据处理和程序逻辑紧密相关。是一个典型的计算机专业面试题,旨在考察者对业务逻辑BUG的识别和解决能力。
面试题
假设你正在开发一个在线购物平台,该平台有一个功能是用户可以添加商品到购物车。购物车中的商品数量和总价需要实时更新。是一个简化的代码片段,用于处理用户添加商品到购物车的逻辑:
python
class ShoppingCart:
def __init__(self):
self.items = []
self.total_price = 0.0
def add_item(self, item, price):
self.items.append(item)
self.total_price += price
def remove_item(self, item):
if item in self.items:
self.items.remove(item)
self.total_price -= item['price']
def get_total_price(self):
return self.total_price
# 测试代码
cart = ShoppingCart()
cart.add_item({'name': 'Laptop', 'price': 999.99})
print(cart.get_total_price()) # 应输出 999.99
cart.add_item({'name': 'Mouse', 'price': 49.99})
print(cart.get_total_price()) # 应输出 1049.98
cart.remove_item({'name': 'Laptop', 'price': 999.99})
print(cart.get_total_price()) # 应输出 49.99
在上述代码中,存在一个业务逻辑BUG。请找出这个BUG,并解释原因。
BUG分析
在上述代码中,`remove_item` 方法存在一个明显的BUG。当尝试从购物车中移除一个商品时,商品存在,它会从列表中移除,从总价中减去该商品的价格。这里存在一个购物车中有多个相同商品,在移除第一个商品后,总价应该减去该商品的价格,而不是减去整个商品列表的总价。
BUG解决方案
为了解决这个我们需要修改`remove_item` 方法,使其能够正确地处理多个相同商品的情况。是修改后的代码:
python
class ShoppingCart:
def __init__(self):
self.items = []
self.total_price = 0.0
def add_item(self, item, price):
self.items.append(item)
self.total_price += price
def remove_item(self, item):
if item in self.items:
self.items.remove(item)
self.total_price -= item['price']
# 确保总价不会变成负数
self.total_price = max(self.total_price, 0.0)
def get_total_price(self):
return self.total_price
# 测试代码
cart = ShoppingCart()
cart.add_item({'name': 'Laptop', 'price': 999.99})
print(cart.get_total_price()) # 应输出 999.99
cart.add_item({'name': 'Laptop', 'price': 999.99}) # 添加第二个相同商品
print(cart.get_total_price()) # 应输出 1999.98
cart.remove_item({'name': 'Laptop', 'price': 999.99}) # 移除第一个商品
print(cart.get_total_price()) # 应输出 999.99
cart.remove_item({'name': 'Laptop', 'price': 999.99}) # 尝试移除第二个商品
print(cart.get_total_price()) # 应输出 0.0
在这个修改中,我们保留了移除商品的操作,从总价中减去该商品的价格。我们添加了一个检查,确保总价不会变成负数,这是因为在某些情况下,用户可能会尝试移除商品的总价超过购物车中的商品总价。
通过这种,我们不仅修复了BUG,还确保了购物车的总价逻辑在处理多个相同商品时的一致性和正确性。
还没有评论呢,快来抢沙发~