Single exit points are a (misguided) attempt to keep method logic simpler.
It is a good example of "throwing out the baby with the bathwater".
Sometimes, multiple exit points make a method clearer, and sometimes they
make it hard to follow or easy to overlook alternate conditions. I don't
hesitate to use them, say, in a simple method that just needs to return a
value based on a switch statement, e.g.,
private string Fooness(string foo) {
switch (foo) {
case "bar":
return "WasBar";
case "foo":
return "WasFoo";
default:
return null;
}
}
It's perfectly self-evident what this is doing, more so (and probably more
efficiently) than artificially creating a return variable, setting that
variable in the switch, and then doing a return of the variable at the end
of the method.
I suppose you could argue that methods tend to grow in complexity over time
and then you could end up with 20 cases, some of them rather large, and then
the returns would be "buried" in all the "noise", and therefore, this is a
bad practice. However, in that case, you should generally refactor this
back down to a short, sweet, simple method anyway, and call other methods to
handle lengthy cases.
I tend to favor "single exit point" designs only when they simplify /
clarify the intent of the code.
--Bob
"Robert Zurer" <ro**********@zurer.com> wrote in message
news:MP************************@news.microsoft.com ...
One minor note on your example; some people suggest that a function
should
have only one exit point, and I generally agree for finctions longer than
a
couple lines. So, your if/else example might become:
object rv = null; // return value
if (person != null)
{
rv = person.FirstName;
}
return rv;
Thanks for your response. It confirms what I thought. With regard to the
single
exit point, is this also for readabilty, or is there another reason?
Recently I have started to use the multiple exit point style because it
does
away with having to read through a lot of conditional logic which won't
get
called.
Robert Zurer