如果语句嵌套过多



我使用以下代码来检查机票是否应该包含折扣。现在有三个if语句,我想知道是否有更好的方法不让它嵌套更少?

ticket_price = current_ticket.display_price
discount_code_session = request.session.get(request.event.discount_code_cookie(), None)
if discount_code_session:
discount_code = Discount.objects.filter(
code=discount_code_session,
event=request.event.pk
).first()
# Make sure discount_code exists
if discount_code:
discounted_tickets = discount_code.tickets.all()
# Why not discounted_tickets: If discounted_tickets empty, then the
# discount code is valid for all tickets.
if not discounted_tickets or current_ticket in discounted_tickets:
discounted_price, original_price = (
discount_code.calculate_discounted_value(ticket_price)
)
ticket_price_dict = {
'original_price': original_price,
'discounted_price': discounted_price,
}
return ticket_price_dict
return ticket_price

在@richflow评论之后,我现在有了这个代码,我认为它更清楚了:

ticket_price = current_ticket.display_price
discount_code_session = request.session.get(request.event.discount_code_cookie(), None)
if not discount_code_session:
return ticket_price
discount_code = Discount.objects.filter(
code=discount_code_session,
event=request.event.pk
).first()
# Make sure discount_code exists
if not discount_code:
return ticket_price
discounted_tickets = discount_code.tickets.all()
# Why not discounted_tickets: If discounted_tickets empty, then the
# discount code is valid for all tickets.
if not discounted_tickets or current_ticket in discounted_tickets:
discounted_price, original_price = (
discount_code.calculate_discounted_value(ticket_price)
)
ticket_price_dict = {
'original_price': original_price,
'discounted_price': discounted_price,
}
return ticket_price_dict
else:
return ticket_price

深度嵌套的if是一种代码气味,尽管不一定是错误的。

一般来说,你希望条件检查快速失败,而不是嵌套它们:

discount_code_session = xxx
if not discount_code_session:
return ticket_price
discount_code = yyy
if not discount_code:
return ticket_price
if discounted_tickets or current_ticket not in discounted_tickets:
return ticket_price
#otherwise
do_the_things_here

你也可以试着在代码审查处发帖,因为这可能是解决此类问题的更好地方。

编辑

这确实进入了代码审查领域,但为了充实一个更完整的答案,以下是本书作为Python指南的内容(与您的要求相关(:

在函数中返回值有两种主要情况。。。[一个是]错误案例。。。或任何其他函数无法完成计算的原因,或任务

在这种情况下最好在检测到不正确的上下文后尽早返回。它将有助于扁平化函数的结构:所有代码在返回之后,由于错误语句可以假定条件满足进一步计算函数的主要结果。。。

但是,当函数的法线有多个主要出口点时当然,调试返回的结果会变得困难,因此可能最好保留一个出口点。。。

我支持第一个参数。其他人选择第二个。阅读整件事,因为它提供了更多的细节来帮助你做出决定。

最新更新