背景
在计算机专业面试中,业务上的BUG分析是一个常见的。这类旨在考察者对实际业务场景的理解能力、定位和解决能力。是一个典型的业务上BUG及其解析。
假设你正在参与开发一个在线购物平台的后端系统。该系统有一个功能是用户可以添加商品到购物车,能够查看购物车中的商品数量和总价。是一个简化版的购物车系统的代码片段,请找出代码中的BUG,并解释原因。
python
class ShoppingCart:
def __init__(self):
self.items = []
self.quantity = 0
self.total_price = 0.0
def add_item(self, item, price):
self.items.append(item)
self.quantity += 1
self.total_price += price
def remove_item(self, item):
if item in self.items:
self.quantity -= 1
self.total_price -= self.items[self.items.index(item)]['price']
self.items.remove(item)
def get_cart_info(self):
return self.quantity, self.total_price
# 测试代码
cart = ShoppingCart()
cart.add_item({'name': 'Laptop', 'price': 999.99})
cart.add_item({'name': 'Mouse', 'price': 19.99})
quantity, total_price = cart.get_cart_info()
print(f"Quantity: {quantity}, Total Price: {total_price}")
分析
在上述代码中,我们需要找出可能存在的BUG,并解释原因。
BUG定位及解析
1. BUG定位:
– 当调用`remove_item`方法时,商品列表中存在重复的商品,`self.items[self.items.index(item)]['price']`这行代码可能会导致索引错误。
2. BUG解析:
– 在`remove_item`方法中,我们检查商品是否存在于`self.items`列表中。存在,我们将从`self.quantity`和`self.total_price`中减去相应的值,并从列表中移除该商品。
– 商品列表中存在重复的商品,`self.items.index(item)`可能会返回多个索引中的一个,这会导致`self.items[self.items.index(item)]['price']`访问的是列表中某个商品的`price`值,而不是当前要移除的商品的`price`值。
– 这会导致错误地从`total_price`中减去错误的金额,并可能留下错误的商品数量。
3. 修正方法:
– 为了解决这个我们可以在移除商品之前先获取到商品的`price`值,再进行移除操作。这样即使列表中有重复的商品,我们也能正确地更新`total_price`。
是修正后的代码:
python
class ShoppingCart:
def __init__(self):
self.items = []
self.quantity = 0
self.total_price = 0.0
def add_item(self, item, price):
self.items.append(item)
self.quantity += 1
self.total_price += price
def remove_item(self, item):
if item in self.items:
price = self.items[self.items.index(item)]['price']
self.quantity -= 1
self.total_price -= price
self.items.remove(item)
def get_cart_info(self):
return self.quantity, self.total_price
# 测试代码
cart = ShoppingCart()
cart.add_item({'name': 'Laptop', 'price': 999.99})
cart.add_item({'name': 'Mouse', 'price': 19.99})
quantity, total_price = cart.get_cart_info()
print(f"Quantity: {quantity}, Total Price: {total_price}")
通过这种,我们确保了即使商品列表中有重复的商品,`remove_item`方法也能正确地更新购物车的状态。
还没有评论呢,快来抢沙发~