【问题标题】:NilCheck fix on safe navigation operator (&.)NilCheck 修复了安全导航运算符 (&.)
【发布时间】:2017-05-27 10:33:21
【问题描述】:

类上的这个简单方法只需使用安全导航运算符运行status 方法。

def current_status
  account&.status
end

但是臭臭的报告这个警告:

MyClass#current_status performs a nil-check [https://github.com/troessner/reek/blob/master/docs/Nil-Check.md]

如何正确编写这样的方法来避免 Nil Check?

我还从thoughtbot 验证了this post,但对于安全导航操作员来说似乎“太多”了。

Ruby 2.3.1

【问题讨论】:

  • 就像 reek 说的,这个mask bigger problems in your source code like not using OOP and / or polymorphism when you should。我认为您需要显示更多代码,至少是包含 current_status 方法的类的相关部分。

标签: ruby ruby-2.3.1 reek safe-navigation-operator


【解决方案1】:

链接post 中“示例 4”的建议很冗长但非常好:

class MyClass
  def initialize(with_account = nil)
    @account = Account.new if with_account
  end

  def current_status
    account.status
  end

  def account
    @account || NilAccount.new
  end
end

class Account
  def status
    "Up!"
  end
end

class NilAccount
  def status
    "Down!"
  end
end

puts MyClass.new(:with_account).current_status
#=> "Up!"
puts MyClass.new.current_status
#=> "Down!"

如果对您来说“太多”,account&.status 可能会很好。

无论您做什么:您都需要尽可能地测试您的代码

【讨论】:

    【解决方案2】:

    嗯,tell-dont-ask 看起来不错,但 Example 4 看起来对于解决这个特定情况来说有点过头了。

    @andredurao 我认为,我们可以使用这个解决方法来通过检查,出于某种原因reek 很好:

    def current_status
      return unless account
    
      account.status
    end
    

    【讨论】:

      猜你喜欢
      • 2011-05-05
      • 2016-04-07
      • 2012-03-13
      • 2015-11-22
      • 2016-04-08
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      相关资源
      最近更新 更多