【问题标题】:Single array argument versus multiple arguments单个数组参数与多个参数
【发布时间】:2013-10-17 23:47:39
【问题描述】:

我看到了一个这样定义和使用的方法:

def mention(status, *names)
  ...
end
mention('Your courses rocked!', 'eallam', 'greggpollack', 'jasonvanlue')

为什么不直接使用数组作为第二个参数,而不是使用 splat 将参数组合成一个数组?

def mention(status, names)
  ...
end
mention('Your courses rocked!', ['eallam', 'greggpollack', 'jasonvanlue'])

这也将允许最后的参数。

def mention(status, names, third_argument, fourth_argument)
  ...
end
mention('Your courses rocked!', ['eallam', 'greggpollack', 'jasonvanlue'], Time.now, current_user)

【问题讨论】:

  • 从 Ruby 1.9 版开始,splat 参数不必放在最后。例如,您可以拥有def mention(status, *names, third_argument, fourth_argument)。作为 Ruby 新手,也许是编程新手,您可能不熟悉 @Adam 在他的回答中使用的术语“代码气味”。它总是一个贬义词。从来没有人听到过,“男孩,你的代码闻起来很香!”

标签: ruby coding-style


【解决方案1】:

splat 感觉很自然,因为这种方法可以合理地应用于单个或多个名称。需要将单个参数放在数组大括号中很烦人且容易出错,例如mention('your courses rocked!', ['eallam'])。即使某个方法仅适用于Array,splat 也经常可以节省击键次数。

另外,你没有理由不能把你的其他论点放在*names

def mention(status, arg2, arg3, *names)
def mention(status, *names, arg2, arg3)

【讨论】:

  • 在现代 Ruby 中甚至落后于 *names
【解决方案2】:

正如 Cary Swoveland 和 vgoff 提到的,定义如下

def foo arg1, *args, arg2
  ...
end

是可能的,所以你的最后一点不成立。


这取决于用例。如果该方法采用自然作为数组给出的参数,那么用户传递数组会更容易。例如,假设一个方法将backtrace_locations(数组)作为其参数。那么最好有:

def foo arg1, backtrace_locations, arg2
  ...
end
foo("foo", $!.backtrace_locations, "bar")

而不是:

def foo arg1, *backtrace_locations, arg2
  ...
end
foo("foo", *$!.backtrace_locations, "bar")

在其他情况下,当用户输入灵活数量的参数时,正如 Sean Mackesey 也指出的那样,当只有一个时,用户可能会忘记元素周围的 [],所以最好要做的事:

def foo arg1, *args, arg2
  ...
end
foo("foo", "e1", "bar")
foo("foo", "e1", "e2", "e3", "bar")

而不是:

def foo arg1, args, arg2
  ...
end
foo("foo", ["e1"], "bar")
foo("foo", ["e1", "e2", "e3"], "bar")
foo("foo", "e1", "bar") # => An error likely to happen

【讨论】:

    【解决方案3】:

    splat 更灵活。只输入 args 比将它们放入数组更容易。

    【讨论】:

    • 你的意思是“输入 args 的元素”吗?
    • 是的,我只是说输入'a','b','c' 比输入['a','b','c'] 更容易且更不容易出错
    【解决方案4】:

    这既关乎简洁的代码,也关乎灵活性。 Splat 为您提供了灵活性,同时显式声明每个输入将您的方法绑定到更接近这些输入对象。如果代码稍后更改怎么办?如果您必须添加更多字段怎么办?你知道你会怎么称呼他们吗?如果您必须在其他地方使用这种方法来处理可变输入怎么办? Splat 增加了很多灵活性并保持方法声明简洁

    列出太多参数也是一种代码味道。

    看看这个:How many parameters are too many?

    在这里:http://www.codinghorror.com/blog/2006/05/code-smells.html

    Long Parameter List:
    The more parameters a method has, the more complex it is.
    Limit the number of parameters you need in a given method,
    or use an object to combine the parameters.
    

    【讨论】:

      猜你喜欢
      • 2011-09-30
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      • 2013-02-26
      • 2012-01-31
      • 1970-01-01
      相关资源
      最近更新 更多