Empty line between methods vs no nested conditionals
All is about to use empty line after return or not?
First example from https://github.com/bbatsov/ruby-style-guide#empty-lines-between-methods
def some_method
data = initialize(options)
data.manipulate!
data.result
end
and second example from here https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals
# good
def compute_thing(thing)
return unless thing[:foo]
update_with_bar(thing[:foo])
return re_compute(thing) unless thing[:foo][:bar]
partial_compute(thing)
end
After combining first and second examples this shouldnt look like that?
def compute_thing(thing)
return unless thing[:foo]
update_with_bar(thing[:foo])
return re_compute(thing) unless thing[:foo][:bar]
partial_compute(thing)
end
Should we use empty line after return?
Ha, good point!
I feel that "Use empty lines between method definitions and also to break up methods into logical paragraphs internally." (for the first example) leaves some room for interpretation. IMHO its not necessary to break up a really simple method body into logical paragraphs. I consider 3 lines to be simple in most cases.
That said, since the return in the middle of a function is a opaque way of flow control, I like the idea of requiring a newline after it. So for your last example, I'd vote for
def compute_thing(thing)
return unless thing[:foo]
update_with_bar(thing[:foo])
return re_compute(thing) unless thing[:foo][:bar]
partial_compute(thing)
end
Although I would avoid returns of that kind when they can easily be transformed into an if-else block.
Although I would avoid returns of that kind when they can easily be transformed into an if-else block.
If you do that, you're likely to trigger Style/GuardClause (edit: oh, not if there's content in the else block)