定义新 API 时使用 struct 作为参数的优点/缺点
我正在编写的 API 适用于继承自 ActiveRecord 的 Ruby 类。我正在尝试编写静态方法以避免泄漏 ActiveRecord 实例。现在所有 API 都需要元组来唯一标识数据库行。
采用以下形式的 API 是个好主意吗:
API1(abc, def, ....) API2(abc, def, ....) 等等
,还是我应该定义一个带有字段的结构来帮助将来的更改?
任何其他想法都非常受欢迎!
The APIs that I am writing are for a Ruby class that inherits from ActiveRecord. I am trying to write static methods to avoid leaking the ActiveRecord instance. All the APIs now need tuple to uniquely identify a database row.
Is it a good idea to have APIs of the form:
API1(abc, def, ....)
API2(abc, def, ....)
and so on
or should I define a struct with fields to help with future changes?
Any other ideas are greatly welcome!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Ruby 中使用结构会很奇怪,而哈希则很正常:
然后可以使用命名参数来调用它,如下所示:
易于扩展,常见的 Ruby 实践,并且易于使某些参数可选。
Using a struct would be strange in Ruby, a Hash would be normal:
And then it could be called using named arguments like this:
Easy to extend, common Ruby practice, and easy to make certain parameters optional.
继续 mu 所描述的内容,这是一个常见的 Ruby 习惯用法,您将看到它有一个方法为自己设置一些默认选项,然后将该方法接收到的选项合并到该哈希中。通过这种方式,您可以确保始终存在一些最小选项列表:
例如,当您的方法输出
:baz
的值时,这会派上用场。现在您不需要先检查它是否存在,只需输出它就知道它总是存在。To continue what mu is describing, a common Ruby idiom you'll see it to have a method set itself some default options and then merge into that hash the options that the method received. This way you can be sure that some minimum list of options always exist:
This comes in handy when your method, for example, outputs the value of
:baz
. Now you don't need to check that it exists first, you can just output it knowing that it would always exist.