[Tutor] Multiple exits in a function...

Alan Gauld alan.gauld at blueyonder.co.uk
Fri Oct 24 13:06:45 EDT 2003


> I trend to write my functions with multiple exits. Usually when some
> test fails, I spit a message(email, print it, or write it to a log
file)
> and get out of dodge. The alternative is usually horrible nested If
> statements even if I flip the logic around.

Yes that's the extreme case. I don't usually object to multiple
returns from a function, provided the returns are at a
consistent level - usually the top.

But the concept of multiple exits being bad is best understood in
the context of structured programming by thinking of the "shape"
of the code as black blocks. Each block should be logically
complete with a single entry point and single exit point.

Inside a block there will be code struictures each with their
own blocks but an any code block level there should be only
one entry/exit path.

The problem with break in particular is that it destroys the
semantic logic of the block.

while <condition> do
     <block>

meand that while the condition is true we continually repeat
the block. You don't need to look inside the block to
understand the enclosing  block. BUT if you use breaks
(and "continue" is only marginally better) inside
the block you can only understand the flow by reading the
inner block as well, because what is really part of the
exit condituon is now in a sepaate test inside the code.
This extra level of reading increases the complexity of
comprehension for the reader.

Of course there are vaid cases where break/continue
does actually simplify the code, but the current trend
in Python to avoid pre loop initialisation (an important
part of comprehending how the loop works!) is not a good
case.

For example:

test = obj.read()
while test < 100 and not eof(foo):
     block here

vv

while not eof(foo):
     test = obj.read()
     if test: break
     block here


In the second example the terminating condition is not
a single boolean expression but split. And now reading
the outer block I have to start reading the inner to
see that the loop actually can terminate due to two
possible scenarios wheras the first version makes it
all clear in the the while statement itself. It also
tells me what the loop initialiser is so that I get
some idea of the potential number of iterations. All
without reading any of the code inside the while.

> Can you point me to some resources to help me wrap
> my mind around this?

If you want a deeper explanation, I suspect you'll
need to look for some of the early books on Structured
Programming from the 1970's, or early 80's. Most modern
ones just mention in passing that single exit is
"a good thing" but give no reasons. (And some very new
ones ignore the research thats already been done and say
its OK!)

Alan G.




More information about the Tutor mailing list