Naming Functions and Variables

It's hard to over-emphasize the importance names bring to the maintainability of code. Unfortunately, there is no formula for generating names, just some good heuristics, and some major "don't"'s.

Bad names reduce code maintainability. Names are bad when they are:

Good names are:

Function Names

A function name should

Avoid names that are:

One common reason for difficulty in finding a short accurate name for a function is because the function violates the Cardinal Rule of Functions.

Variable Names

Most of the rules that apply to function names apply to variable names, as well, except that variables hold objects, not actions, so verb-object and qualified-verb are inappropriate name forms.

In addition, when defining functions that are generic and reusable for a wide variety of tasks, such as a "reverse sequence" function or a "find anywhere" function, there are a number of common conventional short variables names that can and should be used:

Thus, a function that adds a number to every element in a list of numbers could clearly be defined using:

(defun add-number (n l)
  (mapcar #'(lambda (i) (+ i n)) l))

The n and i suggest numbers and the l suggests list. There's nothing wrong with

(defun add-number (num num-list)
  (mapcar #'(lambda (num-item) (+ num-item num)) num-list))

but it's more verbose without being any clearer. On the other hand,

(defun add-number (x y)
  (mapcar #'(lambda (z) (+ x z)) y))

is definitely bad. The variables are too general and easily confused with each other.

For a list of many ways to not name things, check out the naming section of Roedy Green's excellent essay How to Write Unmaintainable Code.


Comments? Send mail to Chris Riesbeck.