文章详情

一、背景

在计算机专业的面试中,业务上BUG的识别与解决是一个非常重要的环节。仅能体现出者对业务逻辑的理解,还能展示其解决的能力和对编程细节的关注。是一个典型的业务上BUG及其解答。

假设我们正在开发一个在线书店的购物车功能。用户在浏览书籍时可以将书籍添加到购物车中。购物车应能够显示用户已添加的书籍列表,并允许用户修改数量、删除书籍或结算购买。是一个简化版的购物车功能实现,请找出并修复存在的BUG。

python

class ShoppingCart:

def __init__(self):

self.items = []

def add_item(self, item):

if item not in self.items:

self.items.append(item)

else:

print("Item already in cart.")

def remove_item(self, item):

if item in self.items:

self.items.remove(item)

else:

print("Item not found in cart.")

def update_quantity(self, item, quantity):

if item in self.items:

self.items[item] = quantity

else:

print("Item not found in cart.")

def checkout(self):

total_price = 0

for item, quantity in self.items.items():

total_price += item.price * quantity

print(f"Total price: {total_price}")

self.items.clear()

# 示例使用

book1 = {'name': 'Book 1', 'price': 12.99}

book2 = {'name': 'Book 2', 'price': 8.99}

cart = ShoppingCart()

cart.add_item(book1)

cart.add_item(book2)

cart.update_quantity('Book 2', 3)

cart.remove_item('Book 1')

cart.checkout()

分析

在这个中,我们需要注意几个潜在的错误点:

1. 当尝试添加一个已存在的项目时,系统会提示项目已存在于购物车中,但没有正确更新项目数量。

2. 当尝试更新一个不存在的项目时,系统会提示项目不存在,但未正确处理数量更新逻辑。

3. 在结算时,项目数量为0,则不应该计算价格。

解答

是针对上述的修复代码:

python

class ShoppingCart:

def __init__(self):

self.items = {}

def add_item(self, item):

if item not in self.items:

self.items[item['name']] = item

else:

print("Item already in cart.")

def remove_item(self, item):

if item in self.items:

del self.items[item['name']]

else:

print("Item not found in cart.")

def update_quantity(self, item_name, quantity):

if item_name in self.items and quantity > 0:

self.items[item_name]['quantity'] = quantity

elif item_name in self.items and quantity <= 0:

self.remove_item(item_name)

else:

print("Item not found in cart or invalid quantity.")

def checkout(self):

total_price = 0

for item in self.items.values():

if item['quantity'] > 0:

total_price += item['price'] * item['quantity']

print(f"Total price: {total_price}")

self.items.clear()

# 示例使用

book1 = {'name': 'Book 1', 'price': 12.99, 'quantity': 1}

book2 = {'name': 'Book 2', 'price': 8.99, 'quantity': 1}

cart = ShoppingCart()

cart.add_item(book1)

cart.add_item(book2)

cart.update_quantity('Book 2', 3)

cart.remove_item('Book 1')

cart.update_quantity('Book 2', 0) # 尝试将数量设置为0,应移除项目

cart.checkout()

在这个修复版本中,我们对购物车中的项目使用字典进行存储,以便于管理和更新。我们添加了对数量的检查,确保在添加和更新项目时数量是有效的。在结算时,我们只计算数量大于0的项目,避免了不必要的计算和显示。

发表评论
暂无评论

还没有评论呢,快来抢沙发~