设计模式:继续

roo*_*oot 0 python refactoring design-patterns

如果您将模式定义为一种巧妙的技巧,可以帮助您以优雅且可能更具可读性的方式解决编程问题[1]。使用该continue语句的设计模式是什么(如果要避免深层嵌套的if语句)?

for item in items:
    if is_for_sale(item):
        cost=compute_cost(item)
        if cost<=wallet.money:
            buy(item)

for item in items:
    if not is_for_sale(item):
        continue
    cost = compute_cost(item)
    if cost > wallet.money:
        continue
    buy(item)
Run Code Online (Sandbox Code Playgroud)

Ser*_*kiy 5

这不是设计模式。但是,当你有很多嵌套循环,并且不清楚那里发生了什么时,那就是代码味道了。我在这里建议做的是两个重构 - Extract MethodReplace Nested Conditional With Guard

首先,提取项目处理以显示您正在做什么:

for(item in items)
   try_to_buy(item)
Run Code Online (Sandbox Code Playgroud)

然后在新方法中应用守卫:

def try_to_buy(item):
   if not is_for_sale(item):
       return

   if compute_cost(item) > wallet.money:
       return

   buy(item)
Run Code Online (Sandbox Code Playgroud)

  • 我已经将你的代码转换为Python。如果您不同意,请随时回滚。 (3认同)