[Tutor] am I missing another simpler structure?
Alan Gauld
alan.gauld at freenet.co.uk
Fri Dec 17 00:37:03 CET 2004
> What makes me lean toward mine still? I'd encountered a general
> injunction to avoid multiple exit point somewhere on the wild web
This goes back to Djikstra's original paper on structured
programming (and he was really thinking about assembler!)
Multiple returns are a source of bugs, especially in maintenance,
but with the advent and popularity of C they have become a
standard ttechnique and with reasonable care they are OK in
practice. The trick is to minimise them or to keep them
collected together in similar patterns. For example in
C it is common to see production code that looks like:
void someFunc(int p1,p2, char* p3)
{
// validate the inputs
if (p1 <0) return BAD_INPUT;
if (p2 > 1000) return BUFFER_ERROR;
if (!p3 or strlen(p3) < MIN_STR) return BAD_STRING;
// real function code here
return result;
}
So there are lots of return statements but they are used
for a very clear purpose and are co-located at the top of
the function. In more modern languages we avoid this kind
of checking with try/except constructs so we would write
something like:
def someFunct(p1,p2,p3):
try:
# do some clever stuff
except anError: raise AttributeError
except anOther: raise ValueError
etc.
This leaves the if/else construct as the other likely place
to have multiple returns, and there it is usually a matter
of personal preference. A try/finally construct will remove
the problem of not freeing resources that used to happen
in C etc.
So in summary, while multiple retirns we a real problem
in the 70's and 80's they have been brought under control
in modern languages such that they are not frowned upon
too much nowadays.
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list