简体   繁体   English

NilCheck 修复了安全导航操作符 (&.)

[英]NilCheck fix on safe navigation operator (&.)

This simple method on a class just run the status method using the safe navigation operator.类上的这个简单方法只是使用安全导航操作符运行status方法。

def current_status
  account&.status
end

But reek report this warning:但是臭味报告这个警告:

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

How can I properly write methods like this to avoid Nil Check?如何正确编写这样的方法以避免 Nil Check?

I've also verified this post from thoughtbot but it seem like "too much" for just a safe navigation operator.我也验证了thoughtbot的这篇文章,但对于一个安全的导航操作员来说似乎“太多了”。

Ruby 2.3.1红宝石 2.3.1

The advice from "Example 4" in the linked post is verbose but pretty good :链接帖子中“示例 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!"

If it's "too much" for you, account&.status might be just fine.如果它对你来说“太多了”, account&.status可能就好了。

Whatever you do : you'll need to test your code as much as possible!无论您做什么:您都需要尽可能多地测试您的代码

well, tell-dont-ask looks pretty good, but Example 4 looks like an overkill to resolve this specific case.好吧, tell-dont-ask看起来不错,但是Example 4看起来对于解决这个特定案例来说有点过头了。

@andredurao I think, we can use this workaround to pass checks, for some reason reek is fine with it: @andredurao 我认为,我们可以使用此解决方法来通过检查,由于某种原因, reek很好:

def current_status
  return unless account

  account.status
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM