4

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]

How can I properly write methods like this to avoid Nil Check?

I've also verified this post from thoughtbot but it seem like "too much" for just a safe navigation operator.

Ruby 2.3.1

AndreDurao
  • 5,600
  • 7
  • 41
  • 61
  • Like reek says, this `mask bigger problems in your source code like not using OOP and / or polymorphism when you should`. I think you need to show more code, at least relevant parts of class that is containing current_status method. – Marko Avlijaš Jan 12 '17 at 10:54

2 Answers2

2

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!

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
0

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
Alex Strizhak
  • 910
  • 1
  • 12
  • 22