【问题标题】:Ways to refactor named arguments with default values使用默认值重构命名参数的方法
【发布时间】:2016-03-15 09:13:24
【问题描述】:

我有一个带有很多命名参数的方法,其中一些带有默认值:

def myClass
  def initialize(a:, b:, c:, d:, e:, f:, g: nil, h: nil, i: nil)
    ...
  end
end

该列表有点难以查看和理解。我正在寻找使这更简单的方法。

对 args 使用哈希,

myClass.new(**args)

有效,但我不能同时拥有带值和不带值的符号。

有没有办法让这更简单?

【问题讨论】:

  • 命名参数提高质量。为什么要删除它们?如果很难看,只需在参数列表中使用换行符。还要看看某些参数是否属于一起,应该收集在结构或对象中。

标签: ruby named-parameters


【解决方案1】:

你可以试试这个

def myClass
  def initialize(args) 
    [:a, :b, :c, :d, :e, :f].each do |a|
      raise ArgumentError.new unless args.has_key?(a)
    end
    ...
  end
end

args 是一个哈希对象。

【讨论】:

    【解决方案2】:

    在某些情况下,一个函数需要如此多的参数,但这通常表明一个函数在一个地方做了太多的事情。

    好的,如果你想这样做,我会把它移到一个特殊的私有方法中:

    class MyClass
      def initialize(*args) 
        args = set_defaults(args)
      end
    
      private
    
      def set_defaults(args)
        # step 1: extract the options hash and check the keys, 
        # if a key doesn't exist so put it in with the default value
        options = args.extract_options! 
        [g: :state, h: 'a name', i: 5].each do |key, value|
          options[key] = value unless options.key?(key)
        end
        # step 2: check the other array elements
        [:a, :b, :c, :d, :e, :f].each do |element|
          raise ArgumentError.new unless args.include?(element)
        end
        # step 3: put them all together again
        args << options
      end
    end
    

    顺便说一句:def className 不起作用。这是class ClassName。另外请看美女ruby style guide - naming

    【讨论】:

    • 如果key 不存在,options[key] 将始终返回nil,因此不需要将其明确设置为nil
    • 没错。目的是展示一种设置默认参数的方法。我将编辑代码并设置一些不同的参数。
    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 2016-06-14
    • 2018-08-14
    • 1970-01-01
    • 2012-08-04
    • 2011-04-03
    • 2015-04-26
    • 1970-01-01
    相关资源
    最近更新 更多