传递散列而不是方法参数 [英] Passing hashes instead of method parameters

查看:105
本文介绍了传递散列而不是方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到在Ruby(和动态类型语言,一般来说)一个很常见的做法是传递一个哈希,而不是声明具体的方法参数。例如,不是使用参数声明方法,而是像下面这样调用:

  def my_method(width,height,show_border)
my_method(400,50,false)

您可以这样做:

  def my_method(options)
my_method({width=> 400,height=& show_border=> false})



我想知道您对此的看法。这是一个好的还是坏的做法,我们应该做还是不做呢?

解决方案

这两种方法都有自己的优点,缺点,当你使用一个替换标准参数的选项哈希时,你会在定义方法的代码中失去透明度,但是每当你使用该方法时,由于使用选项哈希创建的伪命名参数,你就会变得清晰。



我的一般规则是如果你有一个方法(大于3或4)或许多可选参数的很多参数,那么使用一个选项哈希,否则使用标准参数。但是,当使用选项散列时,务必使用描述可能的参数的方法定义来包含注释。


I see that in Ruby (and dynamically typed languages, in general) a very common practice is to pass a hash, instead of declaring concrete method parameters. For example, instead of declaring a method with parameters and calling it like this:

def my_method(width, height, show_border)
my_method(400, 50, false)

you can do it this way:

def my_method(options)
my_method({"width" => 400, "height" => 50, "show_border" => false})

I'd like to know your opinion about it. Is it a good or a bad practice, should we do it or not? In what situation using this practice is valid, and it what situation can it be dangerous?

解决方案

Both approaches have their own advantages and disadvantages, when you use an options hash replacing standard arguments you lose clarity in the code defining the method but gain clarity whenever you use the method because of the pseudo-named paramaters created by using an options hash.

My general rule is if you either have a lot of arguments for a method (more than 3 or 4) or lots of optional arguments then use an options hash otherwise use standard arguments. However when using an options hash it is important to always include a comment with the method definition describing the possible arguments.

这篇关于传递散列而不是方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆