"return" in def
steve at REMOVE-THIS-cybersource.com.au
Tue Dec 30 02:00:59 CET 2008
On Mon, 29 Dec 2008 05:31:17 -0800, Aaron Brady wrote:
> One style of coding I heard about once only permits returns at the end
> of a function. It claims it makes it easier to see the function as a
> mathematical object.
That's silly. You treat the function as a black box: input comes in, and
output comes out. You have no idea of what happens inside the black box:
it could loop a thousand times, take 150 different branches, or take one
of 37 different exit points. From the outside, it's still exactly like a
mathematical object. Internal complexity is irrelevant. This is why
mathematicians can perform algebra on complicated functions like Bessel's
function (of the first or second kind), without needing to care that
actually calculating Bessel's function is quite tricky.
What I think the one-return-per-function style is aiming at is that it is
(sometimes) easier to analyse the internals of the function if there are
few branches. The more complicated branches you have, the harder it is to
analyse the function. Early exits on their own are not the cause of the
complexity: it's the number of branches leading to the early exit that
causes the problem.
Avoiding early exits is an over-reaction to the Bad Old Days of spaghetti
code. But used wisely, early exists can simplify, not complicate, code.
Consider the following:
for item in alist:
if isinstance(item, Ham):
raise ValueError('no ham found')
found_item = None
for item in alist:
if found_item is not None:
if isinstance(item, Spam):
found_item = item
if found_item is None:
raise ValueError('no spam found')
The second version has double the number of lines of code of the first.
It introduces an extra variable "found_item" and two extra if blocks. I
don't think the claim that the version with an early exit is more
complicated than the version without can justified.
More information about the Python-list