Expressive Names

Version 1.10 by chrisby on 2023/11/18 16:24

Names should be chosen as carefully as the name of your first-born child. It should be obvious from reading the code how it works.

  • Names describe purpose. For example, it's better to have a variable unorderedNumbers, which is sorted and stored in orderedNumbers instead of saving both lists in the same variable numbers.
  • Avoid misinformation. For example, ambiguities, confusion with similar names or easily confused characters (l and 1, O and 0).
  • Make differences clear. Avoid very similar expressions and blank words are redundant (a, an, the, info, data).
  • Use pronounceable names. Programming is a social activity that people talk about with others.
  • **Use searchable names. **Searchable means avoiding search conflicts with other independent things with the same name. The length of a name should match the size of its scope. For local counting loops, one letter is sufficient; if the variable is used in several places in the code, it needs a longer name.
  • Avoid encodings. There should be no references to the scope or type of the variable in the name.
  • Avoid mental mappings. The name of a variable should not require mental effort to understand. For example, unusual abbreviations should be avoided.
  • Names of classes consist of nouns or substantivistic expressions.
  • Method names consist of a verb or an expression with a verb. Accessors, mutators, and predicates should be named after their value and follow the JavaBean standard (prefixes: get, set, is, has). For example, getAge(), setAge(...), isFeatureXEnabled() -> boolean, hasPermission() -> boolean etc.
  • Use object creation functions rather than overloaded constructors, as the latter can cause confusion. Overloaded constructors should be declared private, and functions should be used to create instances whose names make the difference clear.
  • No puns or humorous names.
  • Choose one word for each concept. For example, if you use the word "fetch" once for a particular concept, you should consistently use "fetch" instead of synonyms such as "retrieve".
  • Avoid ambiguities as in the word "add" (addition or adding).
  • Domain-specific terms
    • Use terms from the solution domain. Programmers will be reading your code, so use technical language.
    • Use terms from the problem domain. If there are no computer science terms, at least domain experts can refer to them.
  • Add meaningful context. Together with the names of other variables and methods, this context can be created.
  • Do not add superfluous context. Shorter names are better than longer ones, as long as they are clear.
  • Dare to rename things. Your colleagues should be grateful for improvements.