Coding style and else statements

B

Ben Finney

Pete Forman said:
There will always be more potential return points in languages that
support exceptions.

I was specifically referring to 'return' points, i.e. points in the
function where a 'return' statement appears.

In the example to which I responded, the function had multiple
'return' statements, and an 'assert' to aid in finding out when none
of the return statements was hit. I'm making the point that if that
effort is being taken anyway, it's more readable to allow the reader
to see only *one* explicit return at the end, and not write any more
in the first place.
 
M

matt.newville

To my eyes, that's less readable than, and has no benefit over, the
following:

def foo(thing):
if thing:
result = thing+1
else:
result = -1
return result

I wouldn't discount:

def foo(thing):
result = -1
if thing:
result = thing+1
return result

especially if "thing" is the less expected case. This
puts the "more likely" result first, followed by checks
that might modify that result.

But, I also try to avoid adding 1 to things that I test
for Truth:
9

--Matt
 
B

Ben Finney

I chose this to more clearly contrast with the example to which I was
responding; same number of statements but clearer control flow.
I wouldn't discount:

def foo(thing):
result = -1
if thing:
result = thing+1
return result

Yes, that would be my preferred form in most cases.

If I'm writing a function that returns a value, I like to make it
clear by the symmetry of 'result = DefaultValue' and 'return result'
that that's the main gist of the function; the rest of the function is
then geared around changing 'result' before the 'return result'
statement.

My way of being friendly to the reader (admittedly, assuming the
reader will read code similar to the way I read it).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top