是否应将多个 array/hash 查找存储在变量中

Should multiple array/hash lookups be stored in a variable

我最近一直在使用 Reek 来重构我的代码,其中一种味道 DuplicateMethodCall 在数组和散列查找中被调用,例如 array[1]hash[:key] 多次调用时。

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

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

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

  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] 太多了

So I was wondering if multiple array or hash lookups are so expensive

昂贵的通话费并不是不多次通话的唯一原因。它还会在没有真正需要的情况下使代码混乱。考虑这个不那么做作的例子:

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],
    }
  ]
)

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

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

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