This simple method on a class just run the status
method using the safe navigation operator.
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]
I've also verified this post from thoughtbot but it seem like "too much" for just a safe navigation operator.
Ruby 2.3.1
The advice from "Example 4" in the linked post is verbose but pretty good :
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.
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.
@andredurao I think, we can use this workaround to pass checks, for some reason reek
is fine with it:
def current_status
return unless account
account.status
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.