On Sat, 20 Oct 2007 18:56:20 +0900, Alex Young wrote:
> On Sat, 2007-10-20 at 09:23 +0900, Pat Maddox wrote:
>> I concur. There's nowhere that says that functions should have just one
>> exit - it doesn't necessarily make for bad style, or code noise.
> http://www.research.att.com/~bs/JSF-AV-rules.pdf, section 4.13.2, Return 
> Types and Values:

Single-exit actually used to be standard practice, back in the days of
"structured programming".  I'm surprised to see it's still around, but I
suppose AT&T has a point - in procedural languages, if you have multiple
returns in a function, you *could* forget to release the appropriate
resources each time.  And C++, which has no GC, isn't immune to that.

Personally, I've never had a problem forgetting to release the right
resources, because any time I cut and paste a return statement, I copy the
whole block above it too that releases all the resources.  Easy.

I much prefer what I call "straight line" programming - keep on exiting at
errors.  It's the difference between this:

----
if file_exists
  if open
    if lines_to_read
      if read_doesnt_fail
        if not_a_comment
          process_line
        end
      else
        log_an_error
        close_the_File
      end
    else
      log_were_done
      close_the_file
    end
  else
    log_an_error
  end
else
  log_an_error
end
----

and this:

----
unless file_exists
  log_an_error
  return
end

unless open
  log_an_error
  return
end

unless lines_to_read
  log_were_done
  close_the_file
  return
end

unless read_doesnt_fail
  log_an_error
  close_the_file
  return
end

if not_a_comment
  process_line
end
----

Which would YOU rather maintain?  For one thing, I didn't even realize I
forgot to create a loop to read the file until I got through refactoring it
into the second form.  To me, the readability makes it less likely, not
more, that I will forget to release resources.

And if you're really worried about it, you can always wrap a function that
DOES have early returns inside a function that doesn't, and give the
responsibility for resource management to the outer function.  I've done
that a lot.

I've seen programs (this week!) in the first form where the routine is
hundreds of lines.  If you don't have a code-folding editor, it's nearly
impossible to figure out what the logic really is, and where the if/elses
match up.  Doubly so on an 80x25 non-resizable screen where all the indents
make the lines impossibly short.
        
-- 
Jay Levitt                |
Boston, MA                | My character doesn't like it when they
Faster: jay at jay dot fm | cry or shout or hit.
http://www.jay.fm         | - Kristoffer