开发者

Advantages/disadvantages to using struct as a parameter while defining new API

开发者 https://www.devze.com 2023-04-06 17:00 出处:网络
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 needtuple to uniquely

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!


Using a struct would be strange in Ruby, a Hash would be normal:

def self.api1(options)
    # Look at options[:abc], options[:def], ...
end

And then it could be called using named arguments like this:

C.api1 :abc => 'abc', :def => '...'

Easy to extend, common Ruby practice, and easy to make certain parameters optional.


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:

def self.api1(options={})
  default_options = { :foo => 'bar', :baz => nil }
  options = default_options.merge options
  # Now include your code and you can assume that options[:foo] and options[:bar] are there
end

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号