安全导航运算符(&.)上的NilCheck修复

4
这个类上的简单方法只是使用安全导航运算符运行status方法。
def current_status
  account&.status
end

但是 Reek 报告了这个警告:
MyClass#current_status performs a nil-check [https://github.com/troessner/reek/blob/master/docs/Nil-Check.md]

如何正确编写这样的方法以避免空值检查?

我还查看了thoughtbot的这篇文章,但仅使用安全导航运算符似乎有些“过于繁琐”。

Ruby 2.3.1


就像Reek所说的那样,这个“掩盖了你源代码中更大的问题,比如在应该使用面向对象编程和/或多态性时没有使用”。我认为你需要展示更多的代码,至少是包含current_status方法的类的相关部分。 - Marko Avlijaš
2个回答

2
在链接的帖子中,“示例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可能就足够了。
无论你做什么:你需要尽可能多地测试你的代码!

0

嗯,tell-dont-ask 看起来很不错,但是 Example 4 看起来对于解决这个特定情况有些过度。

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

def current_status
  return unless account

  account.status
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接