【问题标题】:Rubocop guard clause dilemma - unnecessary if else VS line too long guard clauseRubocop 保护条款困境 - if else VS line too long 保护条款是不必要的
【发布时间】:2017-03-19 16:15:25
【问题描述】:

我有一段代码,其中有一个带有保护子句的 raise 语句:

def validate_index index
  # Change to SizeError
  raise ArgumentError, "Size of index (#{index.size}) does not matches"\
    "size of vector (#{size})" if size != index.size
end

在这一点上,rubocop 给出了冒犯:

Style/MultilineIfModifier: Favor a normal if-statement over a modifier clause in a multiline statement.

我将我的代码修改为正常 if else case 如下:

def validate_index index
  # Change to SizeError
  if size != index.size
    raise ArgumentError, "Size of index (#{index.size}) does not matches"\
      "size of vector (#{size})"
  end
end

但现在它犯了这个罪行:

Style/GuardClause: Use a guard clause instead of wrapping the code inside a conditional expression.

遇到这种情况怎么办?两者都在引发错误。还有其他选择吗?

【问题讨论】:

  • 您不必盲目地遵循 rubocop 所说的一切。您可以在.rubocop.yml 中禁用 GuardClause 样式检查
  • 您还可以使用 # rubocop:disable 和 # rubocop:enable 禁用内联的单个项目

标签: ruby rubocop


【解决方案1】:

Rubocop 希望你这样写:

def validate_index index
  # Change to SizeError
  return if size == index.size
  raise ArgumentError, "Size of index (#{index.size}) does not matches"\
  "size of vector (#{size})"
end

如果你想走那条路,这取决于你。不管怎样,Rubocop 也推荐:

def validate_index(index)

如果您走原来的路线并忽略 Rubocop,您还应该真正考虑将您的 if != 更改为 unless

unless size == index.size

【讨论】:

    【解决方案2】:

    试试这个:

    这将减少行长,同时引发参数错误

    def validate_index index
      # Change to SizeError
      error_message = 
        "Size of index (#{index.size}) does not matches size of vector (#{size})"
      raise ArgumentError, error_message if size != index.size
    end
    

    【讨论】:

      【解决方案3】:

      你认为用布尔表达式连接什么?例如:

      def validate_index index
         # Change to SizeError
         size != index.size &&
           raise ArgumentError, "Size of index (#{index.size}) does not matches"\
           "size of vector (#{size})"
      end
      

      【讨论】:

        猜你喜欢
        • 2011-10-06
        • 2012-11-25
        • 2011-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-13
        相关资源
        最近更新 更多