Implicit begin?

Certain style guides advise against the use of an explicit begin in method bodies:

# Bad
def method(*args)
  begin
    # code
  rescue
    # code
  ensure
    # code
  end
end

# Good
def method(*args)
  # code
rescue
  # code
ensure
  # code
end

Some developers feel the exact opposite and dislike the implicit begin.

Thoughts?

I prefer the implicit begin since it is more concise and highlights the fact that the entire method is within a rescue. I also see begin as a smell indicating you need to extract a method. Using the explicit begin removes this indicator.

I think it’s fair to assume that readers of the code will know about Ruby’s implicit block creation. Thus, adding an explicit begin is actually a form of duplication.

I’ve heard GabeBW argue that he uses begin to notify the reader that it’s possible the upcoming code could fail. This doesn’t quite convince me, because I’d rather consider Exceptions as exceptional, and ignore them most of the time.

1 Like

Agreed with @benorenstein here.

I like methods to read such that the most important details come first. In most cases, I’d consider exceptions to be less important, since they ideally cover edge cases.

I prefer the implicit begin. In fact, I’ll often use Extract Method to move the begin and rescue clauses into their own methods so that I can eliminate explicit begin clauses.