Re: Control Flow Coding Style

"Avdi Grimm" <[email protected]>
Newsgroups gmane.comp.programming.language-of-the-year
Message-ID <[email protected]>
On Mon, Apr 28, 2008 at 4:55 AM, Michael Hunger <[email protected]> wrote:
>  1) there _must_ be a single point of exit for each method

For me the point of pragmatic compromise falls thus (and I'm assuming
we're only talking about method return, not exceptions):  In general,
only one point of return.  There are a couple of exceptions, though.

1. Short-circuit clauses at the beginning of methods:

  def foo(arg)
    return nil if arg.some_special_case?

    # ... the meat of the method ...
  end

I like to keep these in a separate clause at the beginning of the
method, though; once the primary logic of the method begins, no more
short-circuit returns allowed.

2. Methods where there is a consistent and obvious pattern of returns:

  def bar(arg)
    arg = transform1(arg)
    return arg if arg.ready?
    arg = arg transform2(arg)
    return if arg.ready?
    arg = transform3(arg)
    return arg
  end

What I *don't* like to see is a method that has one obvious return at
the end, and then a second special-case return buried a couple layers
deep in conditionals.  Those are the methods that lead to
head-scratching debugging sessions because you haven't noticed that
the method is exiting early.

>  2) each if must have an accompanying else branch

The longer I write code, the more I think this is a good idea.  I
pretty habitually put in 'else raise "Should never get here"' clauses
in my code.  Yeah, it's a little extra clutter; but the time savings
in catching bad assumptions early is worth it IMO.

-- 
Avdi

Home: http://avdi.org
Developer Blog: http://avdi.org/devblog/
Twitter: http://twitter.com/avdi
Journal: http://avdi.livejournal.com
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.