*Naming Conventions*

Ninereeds stephenhorne100 at aol.com
Sun Jun 3 18:20:18 EDT 2007


On Jun 4, 5:03 am, Thorsten Kampe <thors... at thorstenkampe.de> wrote:

> for validanswer in validanswers:
>     if myAnswers.myanswer in myAnswers.validAnswers[validanswer]:
>         MyOptions['style'] = validanswer

First, for small loops with loop variables whose meaning is obvious
from context, the most readable name is usually something like 'i' or
'j'. It avoids unnecessary duplication and clutter. Of course, just as
physically turning your head to look in the rear view mirror is
necessary in a driving test but stupid for real driving, you are
likely to be penalised for this if you do it in an educational setting
or somewhere else where daft coding conventions are strictly enforced
(I once worked in a company that had library constants 'Zero' and
'One' defined because the coding conventions insisted on absolutely no
unnamed 'magic numbers' - spelling the numbers using letters
apparently didn't count).

Second, when naming a member, you should take into account that
references will already be specifying what the whole class describes.
That is, provide new information where possible, and avoid unnecessary
repetition.

Since Python is dynamically typed, it can be useful for names to
describe the datatype of the content at times (though not to the
Hungarian notation extreme that is common is C code, esp. for
Windows). And while most variable names are nouns, sometimes
adjectives are most appropriate - esp where the noun is already clear
from context.

Based on this, your code might become something like...

  for i in validanswers:
    if myAnswers.current in myAnswers.validList [i]:
      MyOptions['style'] = i

  'i'
      Its obviously a validanswer since it is one of
      the validanswers.

  'myAnswers.current'
      I know its related to myAnswers, but the
      adjective 'current' tells me more about this
      specific member.

  'myAnswers.validList'
      'valid' on its own is useful extra information,
      but suggests a flag field. validList is better
      since it avoids that confusion.

Depending on what myAnswers.myanswer actually holds, it might
alternately be renamed something like myAnswers.uid or myAnswers.id (a
[unique] identifier code identifying the answer) or myAnswers.text
(the text of the answer).

It is also often useful to use a convention where a prefix identifies
whether a name is a (p)arameter, (l)ocal variable, or (m)ember
variable - no prefix for functions, usually. For example, a simple
setter method may logically use the same name for the parameter
specifying the value to write, the member variable to write to, and
(barring a prefix along the lines of 'Set') the method name.




More information about the Python-list mailing list