"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
Rainier [MCT] wrote: As a best practice you should try programming using a single point of exit
within your procedures that way you will never walk into problems like you
are facing right now.
No, instead you'll run into problems where the code is much harder to
read because you need much more indentation to cope with the fact that
simple "I'm done now" situations aren't just returned from.
I've read a lot of code which followed the "only return from one place"
mentality, and a lot of it was hellish.
Careful Jon. The Purity Zealots will come and take you away for such blasphemy.
In a Pre-Exception world it was MUCH more important to follow this logic. That way you have all of
your resource cleanup in one place. Ooops, Only cleaned up the resources in 19 of the exit points
instead of 20.
Of course I often broke the *Rule* even then. When I was *Lucky* enough to inherit one of these
messes, I generally refactored the mess into 2 functions. The outer function handled Setup,Error
handling, and Cleanup. The inner function acted like a Sieve that fell through. This put all of my
error handling in one place and all of my Cleanup in one place.
I had a common point of return from the Outer function and a cleaner flow in the inner function.
So, even though I didn't follow the *Rule*, I did address the issues that the *Rule* was meant to
solve.
Amazingly, once Exceptions are taken into account this *Sieve* logic becomes much more
practical(and common). Of course most of the "return"s are replaced by exceptions, but the concept
is the same.
try/finally for setup/cleanup
try/catch for error handling.
Even though I won't hesitate to use a *Sieve* in my code MOST of my methods follow the "single point
of return" methodology. This mainly comes from a desire to maintain flow control. For instance, if I
want to ensure that ALL code paths (except nasty exceptions) flow through a given point, so I can
put in tracing or something.
In general, if the logic flow doesn't get too convoluted I will use a single point of return,
but I won't lose any sleep over implementing a *Sieve*.
Bill