I’ve recently been working on simplifying a Ruby method that I didn’t write. It’s part of a legacy project that a coworker wrote. In general, we did a pretty good job not accumulating code debt, but there are a few methods that need some love.
The method that I’ve been simplifying was originally a mass of nested if-else blocks. I determined what the method does and simplified the method so there are no longer nested ifs.
Now I want to simplify it even more, and, if possible, I want to eliminate all but one return statement. The method is longer than this, but this is the general concept of what it looks like right now:
def return_bool
return false unless condition1 && condition2
@var = SomeClass.getter(foo)
return true unless var.someProperty != 0
@stuff = @var.getsomething id
return false unless @stuff && somethingElse
data = JSON.parse(@stuff)
@stuff.each do |stuff|
return false if data[stuff['something']] != stuff['anotherSomething']
end
return true
end
I thought about using raise and exception handling to reduce return statements, but if, for example, condition1 is false, it’s not an exceptional situation, I expect it at certain times.
How can I reduce the number of return statements, preferably down to one? If possible, I’d actually prefer to implicitly return if I can.
The sample code isn’t from something that works because Ruby would refuse to execute that method definition.
This is how I would unravel it, but without sample values for any of the local variables or the definition of
SomeClassthere’s no way to test it.