473,748 Members | 5,242 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Coding style and else statements

def foo(thing):

if thing:
return thing + 1
else:
return -1

def foo(thing):

if thing:
return thing + 1
return -1

Obviously both do the same thing. The first is
possibly clearer, while the second is more concise.

Comments?

--
Posted via a free Usenet account from http://www.teranews.com

Aug 28 '06
19 2010

Sybren Stuvel wrote:
Tal Einat enlightened us with:
Actually, the common work-around for this is:

(thing and [thing+1] or [-1])[0]

This works since non-empty lists are always considered true in
conditional context. This is more generic, and IMO more readable.

I think it's not readable at all. It's confusing - you create a
singleton list, only to extract the first element from it and discard
the list again. I'd rather read a proper if-statement.
I agree that an "if" statement is by far more readble; I was referring
only to the dicussion of the "and-or trick", not the entire issue.

I meant to say that:

(thing and [thing+1] or [-1])[0]

is more readable (IMO) than:

thing != -1 and (thing and thing+1 or -1) or 0

- Tal

Aug 30 '06 #11
At Wednesday 30/8/2006 04:47, Tal Einat wrote:
>I meant to say that:

(thing and [thing+1] or [-1])[0]

is more readable (IMO) than:

thing != -1 and (thing and thing+1 or -1) or 0
Interesting to find how different persons feel "readabilit y" - for
me, the later is rather clear (but definitively I prefer an if
statement), and the former simply sucks.
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Aug 30 '06 #12
Tal Einat wrote:
I meant to say that:

(thing and [thing+1] or [-1])[0]

is more readable (IMO) than:

thing != -1 and (thing and thing+1 or -1) or 0
Neither is particularly readable, though I agree that the latter is
worse since it has to have the third option ("0") on the end. But I'd
go with an if statement unless I had a real reason to use something so
unreadable. If you are enamored of such constructs, 2.5 will allow
conditional expressions:

(thing + 1) if thing else -1

Aug 30 '06 #13

Ben Finney wrote:
"Carl Banks" <pa************ @gmail.comwrite s:
However, I have rare cases where I do choose to use the else
(ususally in the midst of a complicated piece of logic, where it's
be more distracting than concise). In that case, I'd do something
like this:

def foo(thing):
if thing:
return thing+1
else:
return -1
assert False

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
For this example, yes. Actually I'd probably never do it in this
particular case. What I mean in general is some rare times (especially
when logic is complex) I prefer to use a redundant control statement
that renders something non-reachable; then I use assert False there.
Carl Banks

Aug 30 '06 #14

Steve Holden wrote:
Carl Banks wrote:
[...]
However, I have rare cases where I do choose to use the else (ususally
in the midst of a complicated piece of logic, where it's be more
distracting than concise). In that case, I'd do something like this:

def foo(thing):
if thing:
return thing+1
else:
return -1
assert False

I think that's about the most extreme defensive programming I've seen in
a while! I can imaging it's saved your ass a couple of times when you've
edited the code a while after writing it.
1. The "assert False" is more for documenting than error checking.
2. The right way to be defensive here is not to have redundant logic.
The above is really something I do rarely only when some other factor
makes the redundant logic a lesser of evils.
Carl Banks

Aug 30 '06 #15
"Carl Banks" <pa************ @gmail.comwrite s:
Ben Finney wrote:
"Carl Banks" <pa************ @gmail.comwrite s:
def foo(thing):
if thing:
return thing+1
else:
return -1
assert False
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

For this example, yes. Actually I'd probably never do it in this
particular case. What I mean in general is some rare times
(especially when logic is complex) I prefer to use a redundant
control statement that renders something non-reachable; then I use
assert False there.
That's the readability problem I'm referring to. Why not ensure that
there is one return point from the function, so the reader doesn't
have to remind themselves to look for hidden return points?

--
\ "Dyslexia means never having to say that you're ysror." -- |
`\ Anonymous |
_o__) |
Ben Finney

Aug 30 '06 #16
Ben Finney <bi************ ****@benfinney. id.auwrites:
Why not ensure that there is one return point from the function, so
the reader doesn't have to remind themselves to look for hidden
return points?
There will always be more potential return points in languages that
support exceptions.
--
Pete Forman -./\.- Disclaimer: This post is originated
WesternGeco -./\.- by myself and does not represent
pe*********@wes terngeco.com -./\.- the opinion of Schlumberger or
http://petef.port5.com -./\.- WesternGeco.
Aug 31 '06 #17
Pete Forman <pe*********@we sterngeco.comwr ites:
Ben Finney <bi************ ****@benfinney. id.auwrites:
Why not ensure that there is one return point from the function,
so the reader doesn't have to remind themselves to look for hidden
return points?

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.

--
\ "Ours is a world where people don't know what they want and are |
`\ willing to go through hell to get it." -- Donald Robert Perry |
_o__) Marquis |
Ben Finney

Aug 31 '06 #18
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:
>>x = 8
foo(x)
9
>>foo(x>1)
2
>>foo(x and 1)
2
>>foo(x or 1)
9

--Matt

Sep 1 '06 #19
ma***********@g mail.com writes:
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 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).

--
\ "Sittin' on the fence, that's a dangerous course / You can even |
`\ catch a bullet from the peace-keeping force" -- Dire Straits, |
_o__) _Once Upon A Time In The West_ |
Ben Finney

Sep 1 '06 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
1402
by: Zhang Weiwu | last post by:
Hello. I have a question that spining around my head for a long time. I prefer to make this kind of if statement: if (!$GLOBALS) Header( 'Location: '.$GLOBALS-> link('/', 'menuaction=forum.uiforum.index') ); But almost all the 'good' php code I saw write it this way:
9
11112
by: Marco Aschwanden | last post by:
Hi I checked the other day a module of mine with pylint. And for some function it told me, that I was using too many return-statements in my code... there were about 5 or 7 of them in my function. Through books I learned, that there should be only 1 return statement in a function. This makes for clear code - they said. I tried to stick to this principle for a very long time... ending up with deeper and deeper nested...
15
3246
by: lawrence | last post by:
Sorry for the dumb question but I'm new to Javascript. I wrote this script hoping to animate some div blocks on a page. You can see the page here: http://www.keymedia.biz/demo.htm Can anyone tell me why these DIVs don't drift to the left as they are supposed to? <script language="javascript">
18
2547
by: craig | last post by:
I am curious about how many of you prefer style 1 vs. style 2, and why. Are there names for these style? style 1: method { }
63
3522
by: Papadopoulos Giannis | last post by:
Which do you think is best? 1. a) type* p; b) type *p; 2. a) return (var); b) return(var); c) return var;
60
3186
by: Eric | last post by:
I thought it might be fun to run a simple vote to discover the most preferred spacing style for a simple if statement with a single, simple boolean test. By my count, there are 32 possible variations for this case. Here is a complete list. AA: if ( a > b ) AB: if ( a > b) AC: if ( a >b ) AD: if ( a >b) AE: if ( a> b )
144
6917
by: Natt Serrasalmus | last post by:
After years of operating without any coding standards whatsoever, the company that I recently started working for has decided that it might be a good idea to have some. I'm involved in this initiative. Typically I find that coding standards are written by some guy in the company who has a way of coding that he likes and then tries to force everybody else to write code the way he likes it, not for any rational reason, but simply for the...
52
2982
by: Sergey Zuyev | last post by:
Hello All I work at software company and we are having a really big discussion about coding styles and it seems that more people prefer statement 1 to statement2 , which was a big surprise to me. Please help us with your comments. Thanks Which way is better way 1 or 2? 1. 'set enable status on CheckboxPrimaryYN
19
3973
by: auratius | last post by:
http://www.auratius.co.za/CSharpCodingStandards.html Complete CSharp Coding Standards 1. Naming Conventions and Styles 2. Coding Practices 3. Project Settings and Project Structure 4. Framework-Specific Guidelines Naming Conventions and Styles
0
9534
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9316
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9241
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8239
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4597
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4867
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2777
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2211
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.