'''''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: MagicNumber''''''s 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 Minutes''''''Per''''''Hour = 60; This is good, not because the value is likely to change, but so as to reduce confusion with Seconds''''''Per''''''Minute, which is also 60. const Seconds''''''Per''''''Minute = 60; const Minutes''''''Per''''''Hour = 60; const Seconds''''''Per''''''Hour = Seconds''''''Per''''''Minute * Minutes''''''Per''''''Hour; ...and so on, say with... const MaxDays''''''Per''''''Month = 31; ... [Unfortunately, Seconds''''''Per''''''Minute 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? * Use complete names where an object is referenced from more than one place. Abbreviate for local scope only (for example, Enumeration e = getEnumeration()) ''Bad idea, use pronounceable names for all variables, is it really so tough to type "each" rather than "e", readability is more important.'' ** [Does using full words ''really'' improve readability for local variables' names? Is function(first, second) {return first < second;} easier to read than function(a,b) {return a < b;}, for example? (Or are there better choices than either of those?) -DavidMcLean] *** Each is readable, neither is descriptive as to what it is. What it does is. The use of complete names as indicated above was with regard to "an object .. referenced from more than one place". I take that to mean outside of local scope. Local variables are not addressable directly from outside. They may be via calling parameters however. *** I prefer names over single characters when referring to understandable by name artifacts which can acted upon by artifactories to produce other understandable by name artifacts . single characters are more readable when used in expressions like ''a=(x*b)+c'' *** example: DinnerTimeFood = function Recipe(ingredients, instructions) is more Humanly readable than is -> a = function b(c,d) -- DonaldNoyes * Choose a name that describes WHAT the object does, instead of how it does it. Review your data structures and functions to avoid using word tricks to keep track of all your variables. * Isolate or eliminate variables that are not immediately needed. The point isn't so much that you have to limit the number of variables, but rather simplify your design to avoid such large proliferations of variables in the local NameSpace that you have to resort to a (subjectively) over-complicated SystemOfNames such as HungarianNotation. * If we stipulate that a variable naming convention never replicate information the compiler checks, then HungarianNotation can be useful today. For example, many people encode scope in names: using capitals for globals (like class names), "a" or "an" ''("my" sounds silly, is someone going to steal your variable?)'' as a prefix for instance variable and lowercase with no prefix for stack variables. The cost is low because only a few things need distinguishing. ''See SmalltalkBestPracticePatterns for a better SystemOfNames.'' * The more a name is referenced, the shorter it should be. For a frequently referenced name, put a comment next to it [declaration?] to explain any abbreviations it may contain. ** ''Bad idea, don't abbreviate, use readable speakable names like each, next, index, count, it won't kill you and it'll make the code much much more readable. The variable name is the comment, you don't need anything else.'' ** {I disagree. Excessive use of long variable names makes code harder to read, at least for my eyes. For example, the patterns of math equations are easier to see if we stick with single letters. A similar principle applies to code IMO. Define the "performers" to the side of the main stage, not on it. I'm okay with "count" by itself, but if you have "fooCount", "barCount", "elephantCount", "mississippiCount" etc. all over, then consider "fooCnt" etc. Comment the declaration of the variable to indicate it is "quantity of foo's". If somebody forgets, they can check the comment next to the declaration. -t} ** -- JonGrover ** ''I tnk vrbl nms tht r abrvtd r hrd 2 rd, bt mby tht_s jst me.'' ** We use abbreviations all the time in English. Your example is not representative because the words are only used once. I wouldn't want to see the full name of NASA spelled out on every reference. Describe it at the declaration, but please don't repeat it on every usage, or I'll bop you in the head. var NASA as String; // National Aeronautics and Space Administration (USA) var emplName as String; // Employee name ** ''We use abbreviations in English that are used frequently enough to become familiar. A variable name used only a few times is not familiar nor will it become familiar. However, a variable name, or a function name, that is used throughout a program might be a good candidate for abbreviation, but then it should really be an abbreviation. A method called "Rndr", used throughout a rendering application, is probably fine but a variable or method called "p" tells us nothing.'' (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 "Last''''''Name, First''''''Name Middle''''''Initial", in all UPPER CASE, but there's no enforcement or processing.) -- JeffGrigg ---- ''moved from Good''''''Symbol''''''Names'' 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 1. Avoid Encodings 1. Don't be too cute 1. Most meanings have multiple words. Pick ONE 1. Most words have multiple meanings 1. Nouns and Verb Phrases 1. Use Solution Domain Names 1. Also Use Problem Domain Names 1. Avoid Mental Mapping 1. Nothing is intuitive 1. Avoid Disinformation 1. Names are only Meaningful in Context 1. Don't add Artificial Context 1. 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 A''''''ccountVisitor, 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: ** IAm(present tense verb), Example: IAmEnabled ** IHaveBeen(past tense verb), Example: IHaveBeenEnabled ** (target singular noun)Is(present tense verb), Example: theEditBoxIsEnabled ** (target singular noun)HasBeen(past tense verb), Example: theEditBoxHasBeenEnabled For class methods, the object name will serve as the target noun, so the patterns reduce to: ** Is(present tense verb), Example: theEditBox.IsEnabled() ** HasBeen(past tense verb), Example: theEditBox.HasBeenEnabled() 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. ** (target singular noun)Is(present tense verb), Example: theEditBoxIsEnabled() ** (target singular noun)HasBeen(past tense verb), Example: theEditBoxHasBeenEnabled() 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 MeaningfulName''''''s? They both talk about the same thing, right?) * Because GoodVariableNames are MeaningfulName''''''s? * And should the name of this page be Good''''''Variable''''''Name? (EditHint 2: StuckWithBadVariableNames) --------- See also: MostImportantWordsOnLeft