Naming Variables

After the programmer determines what type of data a variable will hold, they must come up with a good variable name to describe that data.  For example, if I will create a variable that holds my age, I would need to determine the appropriate data type and the appropriate variable name.  Since ages cannot usually hold a decimal point, it would be appropriate to use an int data type for my variable.

int age;

Variable should have a great descriptive name.  age would be a descriptive name that describes what is inside that variable. However: int a; is not descriptive.  What does a stand for?  What does it mean?  A colleague would not be able to look at that variable and quickly understand what the variable holds.

When you declare a variable, you should pick a name that explains its purpose. For example, it is better to use a descriptive name, such as salesTax, than a terse name, such as st.  In this regard, Java variable names should be descriptive and meaningful.

Oracle Java Docs outline these Java conventions for naming variables:  ( https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html)

  • Variable names are case-sensitive.
  • A variable’s name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign “$“, or the underscore character “_“. The convention, however, is to always begin your variable names with a letter, not “$” or “_“. Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it’s technically legal to begin your variable’s name with “_“, this practice is discouraged.
  • White space is not permitted.
  • Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well.
  • When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadencespeed, and gear, for example, are much more intuitive than abbreviated versions, such as sc, and g.
  • The name you choose must not be a keyword or reserved word in Java.
  • If the name you choose consists of only one word, spell that word in all lowercase letters.
  • If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention.
  • If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.