是否应将多个数组/散列查找存储在变量中

时间:2017-07-05 11:31:07

标签: ruby refactoring reek

我最近一直在使用Reek来重构我的代码,其中一个气味是 DuplicateMethodCall ,正在调用数组和哈希查找,例如array[1]或多次调用时hash[:key]

所以我想知道多个数组或散列查找是否如此昂贵,我们应该将它们存储在变量中而不是直接调用它们,这就是每个人根据我的经验做的事情。

我会毫不犹豫地在变量中存储多个对象方法调用(特别是如果它是一个DB调用),但是对于数组和散列查找这样做会觉得有点过分。

例如,我会收到这段代码的警告:

  def sort_params
    return [] if params[:reference_letter_section].nil?

    params[:reference_letter_section].map.with_index(1) do |id, index|
      { id: id, position: index }
    end
  end

但我觉得将params[:reference_letter_section]存储在自己的变量中太多了

2 个答案:

答案 0 :(得分:2)

  

所以我想知道多个数组或哈希查找是否如此昂贵

昂贵的通话不是多次不拨打电话的唯一原因。它也使代码混乱而没有实际需要。考虑一下这个不那么人为的例子:

Order.new(
  name:       params[:order][:name],
  total:      params[:order][:total],
  line_items: [
    {
      product_name: params[:order][:line_item][:product],
      price:        params[:order][:line_item][:price],
    }
  ]
)

即使这些散列访问非常便宜,但出于可读性原因,提取它们仍然有意义。

order_params     = params[:order]
line_item_params = order_params[:line_item]

Order.new(
  name:       order_params[:name],
  total:      order_params[:total],
  line_items: [
    {
      product_name: line_item_params[:product],
      price:        line_item_params[:price],
    }
  ]
)

答案 1 :(得分:0)

重复哈希查找表示这两行代码之间的耦合。这可能会增加理解代码所需的时间,并且在更改代码时可能会成为摩擦源。当然,在这样的小方法中,成本相对较低;但是如果两行代码分开 - 例如在不同的类中 - 耦合的影响将会更加昂贵。

这是您的方法的一个版本没有重复:

def sort_params
  reference_letters = params[:reference_letter_section] || []
  reference_letters.map.with_index(1) do |id, index|
    { id: id, position: index }
  end
end
相关问题