Regarding coding style

Micah Cowan micah at cowan.name
Sun Mar 9 02:27:16 CET 2008


dave_mikesell at fastmail.fm writes:

> On Mar 8, 2:38 am, Steven D'Aprano <st... at REMOVE-THIS-
> cybersource.com.au> wrote:
>> On Fri, 07 Mar 2008 20:57:32 -0800, dave_mikesell wrote:
>> >> x = get_stuff(store)  # Get the stuff what was brought at the store.
>>
>> > Perfect example of an unnecessary comment.  The variable and function
>> > names are commentary enough.
>>
>> "x" is a terrible name. What does it mean? Nothing.
>
> Right, that's a problem with the code.  A comment only masks the bad
> smell.  'x' should be renamed to something meaningful, obviating the
> need for comments to follow it around.
>
>> There's only three places x is an appropriate name:
>
>> (1) A meta-syntactic variable like foo, bar, spam, ham, parrot.
>>
>> (2) Library functions, where x stands for a generic argument, usually a
>> number, e.g. def sin(x).
>>
>> (3) Throw-away code you don't need to maintain.
>
> I use single letter variables where their scope is very small.  e.g.,
> tight loops, small functions,  etc.  I even use them as class members
> where they make sense in the domain.  x, y, z for 3d vectors, r, g, b,
> a for colors, etc.

This was a two-line code sample. Since you've indicated you use such
names where their scope is small, it's rather hard to say, without
more information, whether using "x" for this code generats a "smell"
or not. For that small amount of code, I'd say it doesn't.

I find that long names in short code segments actually detract from
readability. In the very first section of their book "The Practice of
Programming", Kernighan and Pike recommend using "descriptive names
for globals, short names for locals," saying "within a function, <n>
may be sufficient, <npoints> is fine, and <numberOfPoints> is
overkill." 

As you point out, even for non-super-small scopes, such as class
members, it can make more sense to use single-letter names; I'd
consider red, green, blue and alpha to be unnecessary names, and it's
hard to improve on the x, y and z you gave as an example.

-- 
Micah J. Cowan
Programmer, musician, typesetting enthusiast, gamer...
http://micah.cowan.name/



More information about the Python-list mailing list