I am SO glad to see this opinion being expressed. One of my professors
drilled into us the need to have a single point of return, combined
with always handling the nominal case *first*, and he was unyielding
on it. I always thought it had the opposite effect of the one he
claimed: it forced me to save return results in temporary variables
and to wade through scores of lines of code that no longer had
anything to do with the scenario I was debugging or testing,
carefully, so that I didn't risk losing my place or missing something
important. I gave up this practice long ago but still occasionally
think about it. This is the first mention of it I've seen since I had
that professor, and it validates my feeling that exceptional case
first, return as soon as possible is the better principle.
Much of what you have here can be both correct or incorrect depending on
platform and/or language.
Exceptional versus nominal first:
If you are dealing with input validation (what code contracts is
supposed to aid with in .NET 4.0), you would code exception first, as
you might as well throw out items that will not make it through the
routine. This is more efficient, especially in "traffic cop" type of
routines (of course, inversion of control can eliminate some of this
argument). There are probably other reasons to have exception first, but
this is a primary case. Once again, the code contracts may eliminate the
need to explicitly code some of this.
Outside of these types of cases, i would aim for nominal first, but I
also subscribe to a TDD approach to development, so solving the problem
with as few lines of code as possible is the first step.
Single Point of Return:
The reason for the "rule" is discipline. If you try to adhere to the
rule first, you find that you generally end up with better code. The
reason is you do not end up taking sloppy short cuts (aka, kludges) to
get through the routine.
As with all "rules", there are instances where you have to break it.
But, if you adhere first to the rule and then break when needed, you
find you have better code.
Professors are there to drill in the basics. over your college career,
you generally find the classes more rigid at first and less as you get
to upper level courses. If you had an upper level professor that
subscribed to ALWAYS, you probably were dealing with an ideologue.
Regardless, if they don't initially teach things as rules, you do not
take the ideas seriously.
Peace and Grace,
--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
Twitter: @gbworld
Blog:
http://gregorybeamer.spaces.live.com
My vacation and childhood cancer awareness site:
http://www.crazycancertour.com
*******************************************
| Think outside the box! |
*******************************************