Hi Edward,
|| I was taught that one should have
|| a single exit point in every function.
You was taught wrong!
Here's the correct version.
One should have a single exit point in every function where it makes more
sense. And as many more as necessary when it makes sense.
No, actually you were taught correctly enough - for the stage you were at.
For a beginner programmer the absolute rule makes it easy to form good enough
habits. As an experienced programmer, you will be making your own choices -
breaking some rules and finding out that things are actually a bit better
(when you get it right).
It's impossible to teach the version that I gave because it just reeks of
the need for experience.
Personally I like to get my error checking over and done with at the top
of a routine. Once those checks are done, everything below can assume that the
parameters are valid (for example).
Having a Boolean which gets tested means not knowing until the very end
whether a bad parameter causes an exit or some extra processing somewhere
below. Or it's made clear by extra levels of indentation which does nothing
for the conservation of space (a valuable commodity).
Sub Foo (TheArg)
If ItsWrong (TheArg)
Exit Sub 'Nuff said.
End If
'From here onwards TheArg is good stuff...
: : :
'Plenty more but not too much.
: : :
End Sub
When you rigidly stick to the 'Use A Boolean and Keep Checking It' rule to
control program flow, you can sometimes get tied in knots as bad as GoTos used
to be - trying to fight your way out of the code to reach the bottom. In these
cases a simple Exit Sub will cut the crap quite nicely. ;-)
One example, is search loops. The value gets found in the middle of the
loop. All I want to do is return it. There's a wonderful keyword - Return -
created just for the job and I'm happy to use it. If we weren't supposed to
exit before the end, languages would never provide Returns and Exit Sub.
If there's concern that a subsequent programmer will overlook the abrupt
exit - document it in lovely big capitals at the top of your routine (or not).
Seriously, though, it's easy enough to list the terminating conditions of a
routine.
Are you being 'being picky'? Well, let's change the phrase to 'being
choosy'. And now, because you're asking the question, we change it to 'giving
the matter consideration'. All of a sudden it sounds like a good idea to me.
Something that indicates the development of maturity and your own style.
)
Regards,
Fergus