【问题标题】:return early vs if in ruby code提前返回 vs if 在 ruby​​ 代码中
【发布时间】:2016-10-19 05:44:15
【问题描述】:

我看到了两种写同一件事的风格:

def find_nest(animal)
  return unless animal.bird?
  GPS.find_nest(animal.do_crazy_stuff)
end

def find_nest(animal)
  if animal.bird?
     GPS.find_nest(animal.do_crazy_stuff)
  end
end

哪一个更正确/更可取/遵循最佳实践?还是没关系?

【问题讨论】:

  • 我会写GPS.find_nest(animal.do_crazy_stuff) if animal.bird?
  • @Stefan 我总是想出糟糕的问题示例:P
  • @Stefan:在值很重要的表达式的情况下,我发现修饰符条件令人困惑。仅在“语句”中使用它们,并且仅在主要表达式不太长时使用(否则它会将修饰符推到视线之外)
  • @FilipBartuzi 因为你的问题被标记为 oop - 当然最好有一个 Bird 类(Animal 的后代)并在没有的情况下实现 Bird#find_nest参数为def find_nest; GPS.find_nest(do_crazy_stuff); end

标签: ruby coding-style guard-clause


【解决方案1】:

根据Ruby style guide

当您可以断言无效数据时,首选保护子句。保护条款 是函数顶部的条件语句,它作为 尽快。

# bad
def compute_thing(thing)
  if thing[:foo]
    update_with_bar(thing)
    if thing[:foo][:bar]
      partial_compute(thing)
    else
      re_compute(thing)
    end
  end
end

# good
def compute_thing(thing)
  return unless thing[:foo]
  update_with_bar(thing[:foo])
  return re_compute(thing) unless thing[:foo][:bar]
  partial_compute(thing)
end

【讨论】:

    【解决方案2】:

    这显然是个人喜好问题。但我更喜欢早点回来。它不仅使代码“更扁平”且更易于阅读,而且还可以很好地适应检查次数。例如:

      def create_terms_of_service_notification
        return if Rails.env.test?
        return if current_user.accepted_tos?
        # imagine 5 more checks here. 
        # Now imagine them as a mess of nested ifs.
    
        # create the notification
      end
    

    【讨论】:

      【解决方案3】:

      这个:}

      def find_nest(animal)
        GPS.find_nest(animal.do_crazy_stuff) if animal.bird?
      end
      

      【讨论】:

        猜你喜欢
        • 2019-05-21
        • 1970-01-01
        • 1970-01-01
        • 2017-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-23
        相关资源
        最近更新 更多