Good Variable Names

How To... Guidelines with strict emphasis only on a positive outlook.


The most obvious benefit to GoodVariableNames can reduce the need for extensive comments, producing SelfDocumentingCode. When reading code peppered with well thought out variable names it's like reading poetry or music.

I prefer to have some sort of description of my design that can be translated into code by anybody who looks at it. The code I create may not necessarily be exactly the code you create, but it will do the same job. We both worked off of the same sheet of music. -- MartySchrader

If it can be done automatically, why not get a machine to do it? And if you can do that, then you've just written code... See TeachMeToSmoke. -- BenAveling

Some variable name choices may at first glance seem odd or an unnecessary waste of time, but closer inspection can reveal subtleties and depth behind a program's inner workings as well as the programmer's future intent for direction of the program (if any), and state of mind (if any).

The philosophy behind DonKnuth's LiterateProgramming methodology is that code should be written primarily to communicate its purpose to humans.

SystemOfNames useful tip: use a thesaurus to name objects.


Examples:

MagicNumbers are literal values that appear in a program, seemingly from out of the blue, and it's unclear from the code what they mean. It's generally better to replace magic numbers with constants.

const int MinutesPerHour = 60;
This is good, not because the value is likely to change, but so as to reduce confusion with SecondsPerMinute, which is also 60.
const SecondsPerMinute = 60;
const MinutesPerHour = 60;
const SecondsPerHour = SecondsPerMinute * MinutesPerHour;
...and so on, say with...
const MaxDays?PerMonth = 31;
...
[Unfortunately, SecondsPerMinute is not always 60. On very rare periodic occasions, it is 61.] In other words LeapSeconds


Naming Considerations

What constitutes a good variable name is wholly dependent upon many different factors. Programming language, programmer's language (native spoken tongue), limitations in hardware, software, and time constraints often lead to humorous BadVariableNames. See also DealingWithCumbersomeEnvironments.

How about some principles?

         var NASA as String; // National Aeronautics and Space Administration (USA)
         var emplName as String;  // Employee name
(This last point is why I think the "self." notation of Python is a good idea - you don't have to encode scope in name when you have syntax for it. Although I use "s.", because the construct is used often enough to deserve as short a name as possible. For the same reason, I dislike PHP's "$this->". -- PanuKalliokoski)


Its often a good idea to include units in a name. Using variable names like "distanceToTargetInCentimeters" Vs "distanceToTargetInInches" can avoid confusion. Some people would suggest using an underscore instead of the word "In" in such names. It acts as punctuation, separating the purpose of the variable from its units: "distanceToTarget_centimeters". It's Hungarian at a more abstract level (and with meaningful words instead of cryptic letters). -- DaveWhipp

It's also Hungarian in the sense that it would be superseded by a better type system, one which included checks of units and dimensions. -- DaveHarris


I still want a ProgrammersThesaurus. -- CurtisBartley


Names should be meaningful within their context.

"x" and "y" are easily understood in the context of work on a 2D plane. "Name" is meaningful within the context of an employee. But, outside the context of an employee object, you'll need to say more - "EmployeeName?". -- JeffGrigg

Name is perfectly valid as an attribute of a particular class. If you have a base class of Person with a derived class of Employee then you can use the same Name attribute for the Employee objects as any other object derived from Person. Any objects from Person-derived objects will have their own Name associated with them. The example you give implies that both a personal name and an employee name, for instance, might be manipulated within the same context. Is what I'm reading correct? -- MartySchrader

Actually, I had in mind some external code that (for some crazy reason ;-) needs temporary local variables to store Employee.Name, Customer.Name, Bank.Name, etc. Say...it's looking for relationships between Employee.Name & Customer.Name, on the assumption that some employees may also be customers. (We'd show "possibly related" records to the user, who does the reasearch to see if there really is a relationship.)

Thus, within any given object, "Name" is sufficient: It's the name of this object. But when working with multiple objects, further qualification is needed.

-- JeffGrigg

Actually, both name and employee.name may be inadequate. I don't know what a name is! which of the following is intended?:

Dave
Dave Whipp
Whipp Dave
Mr Dave Whipp
Mr Dave P. Whipp
DaveWhipp
Even if it truly doesn't matter, then perhaps the variable name should tell us that. Of course, if name is of class Name, rather than a String, then the class itself would give us the additional information. -- DaveWhipp

Consider the system I happen to be working on now. We use "NAME". It could be any one of the above. It could be a different for each employee. It's in whatever format(s) the user finds pleasing. (We recommend "LastName, FirstName MiddleInitial", in all UPPER CASE, but there's no enforcement or processing.) -- JeffGrigg


moved from GoodSymbolNames

As many have noticed, most of the pages here about symbol (variables, methods, classes) names are about how not to name rather than how to name.

Here is a great paper that will give us a start in reversing the trend:

http://www.objectmentor.com/publications/naming.htm

...and its index:

  1. Use Pronounceable names
  2. Avoid Encodings
  3. Don't be too cute
  4. Most meanings have multiple words. Pick ONE
  5. Most words have multiple meanings
  6. Nouns and Verb Phrases
  7. Use Solution Domain Names
  8. Also Use Problem Domain Names
  9. Avoid Mental Mapping
  10. Nothing is intuitive
  11. Avoid Disinformation
  12. Names are only Meaningful in Context
  13. Don't add Artificial Context
  14. No Disambiguation without Differentiation

Generally I agree with the articel above, but disagree with "Use Solution Domain Names." The argument is that code should be maintained by "computer scientists" who should not have to understand what the code is used for, ergo use "computer science" names rather than "application domain" names. This is to avoid having the programmer map from an application domain name to a computer science name. In most programs new features, changes, and corrections are provided by users in the application domain language. It simplifies finding either the code to be modified or a home for new code if the code is already in the application domain name. At that point, one can decide what computer science solution to be used to address the application domain issue.

If the problem domain doesn't have names for lists, maps, factories, visitors, etc, a SystemMetaphor may help in developing a consistent vocabulary.

What if the problem domain doesn't have names for lists, maps, factories, visitors, etc.? A SystemMetaphor won't provide these. They are names from the solution domain. -- EricHodges

Why should anyone outside of a class factory care that a class factory pattern was used to provide the result? The operation is to get some well known object for use and the using code does not need to know where the object came from nor how it was created. The purpose of the class factory pattern and other creation patterns is to hide the creation method form the using code. One does not need to expose the selected implementation by attaching "Factory" to the end of a method name. A similar argument can be made for other "solution" names. If sets of objects are used, the problem domain will most certainly have at least one name to reference the set. Beyond that, one should not care how the set is implemented, as an array, a linked list, a database table, etc. -- WayneMack

So if I create a new visitor or map class as part of the solution, I shouldn't name it in such a way that future developers will know that's what it is? The folks who inherit my code will care that a factory pattern was used. I care when I inherit other folks' code. The fact that a method hides the creation method shouldn't be hidden along with the creation method. -- EricHodges

I would suspect that someone using the new class is probably more interested in how it relates the business objects to which it is being applied and to the methods the class supports. Those that are really interested in the implementation can look at the source code. Those that have read the Patterns book will probably be able to recognize the pattern, while those who have not will not be aware of the significance of the name. Users of the class will not care how one chose to implement it. Those who need modify the implementation of the class do not really care what the inspiration of the class might have been, they merely want to make it behave differently. -- WayneMack

They shouldn't have to look at the implementation of AccountVisitor, say, to know that it is a visitor. They know it visits accounts because that's in the name as well. They won't care how it is implemented either way. If they need to modify it, it's important that they know it plays the visitor role. -- EricHodges


Boolean Rules

I usually find that naming conventions group together based on the type of data references, rather than differentiation based on variable vs. object vs. method. My simple test for an appropriate boolean name is whether if it is gramatically correct in the following test sentence:

If [boolean name], then action is taken.

For local variables and class variables, I usually find the following basic patterns work:

For class methods, the object name will serve as the target noun, so the patterns reduce to:

For procedural methods, I usually will include the target name to avoid name collisions within the project. If there are name collisions between a local variable and the method, I will usually change the local variable to the first person (IAmXXX, IHaveBeenXXXX) version. The compiler may be able to differentiate between the variable and the method, but other programmers may not.

A side effect of this approach is that all variables and objects should be singular not plural. This avoids jarring lines like:

if theEditBoxes.IsEmpty?() {}

An alternatvie naming to to use a qualifier like like "List" resulting in

if theEditBoxList.IsEmpty?() {}

Hmm. My solution to this is to use Boolean methods that tell me something, like IsDoorOpen?() or IsPositionerReady?(). That way the code reads like a simple evaluation of a condition, although acquiring the answer to the conditional question was through the use of a call.


(EditHint 1: should this page be merged with MeaningfulNames? They both talk about the same thing, right?)

(EditHint 2: StuckWithBadVariableNames)


See also: MostImportantWordsOnLeft


EditText of this page (last edited December 12, 2014) or FindPage with title or text search