ruby-style-guide icon indicating copy to clipboard operation
ruby-style-guide copied to clipboard

Empty line between methods vs no nested conditionals

Open gutekk opened this issue 7 years ago • 2 comments

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?

gutekk avatar Apr 10 '18 10:04 gutekk

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.

moritzschepp avatar Apr 10 '18 23:04 moritzschepp

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)

gareth avatar Apr 12 '18 10:04 gareth