My name is Variable.
The subject of variable naming came up on the KinoSearch mailing list a little
while back. This blog entry started off as part of an email reply to that
thread, but then I thought better of it...
As a base, I agree with all the general rules regarding names laid out in
the Slash Style
Guide:
- Only iterators get single-letter names.
- Scalars are singular.
- Composite variables — e.g. arrays and hashes — are plural.
- References to compound variables are also plural.
- Constants get all caps.
- Underscore separation rather than CamelCase.
-
Names should be descriptive — e.g. "$story_count" is preferable to
"$sc" (to quote the Slash example).
The only qualification I would make is that the preference for underscores over
CamelCase is language-dependent — for instance, CamelCase is preferable for
Java and JavaScript.
On top of those, here are a few more:
-
Names should be pronounceable. If I'd written the C standard library
(heh), "strcmp" would be "scomp". Pronounceable variable names are easier
for the eye to parse — they look like words, so we absorb them as whole
words rather than collections of distinct, individual letters.
-
Avoid overload overload. It's generally accepted that generic names like
"data" and "var" should be avoided because they are unclear. However,
names which may be sufficiently specific in certain contexts may be
ambiguous in others. The word "index", for example, is horrendously
overloaded in the context of searching. Does it refer to an existing
inverted index on the file system? The act of indexing? Or an array
index? Solution: never use "index" as a variable name.
-
Class names should always be singular, so that individual instances can
follow the scalar naming pattern and composites can follow the composite
naming pattern. Say you had a class called "Taxes". What do you name an
array of objects belonging to the Taxes class? "taxeses"?
-
The shortest unambiguous name should be used, because longer names yield
more multi-line statements. Perhaps I take this farther than most, using
"cat" for "category" and "nick" for "nickname" when others might use the
full form.
Each of these rules is made to be broken, of course... but collectively, they
seem to have served me well.
posted 2007-Sep-05 20:53
:: permalink