Variables – Naming Syntax and Conventions

The programmer has a great deal of freedom in creating names for variables.  However, there are two categories of constraints that programmers follow: syntactic requirements imposed by the programming language and conventions used to make programs more readable.

Syntactic Requirements

These rules vary somewhat from one programming language to another.  They are imposed by the compiler or translator to allow unambiguous parsing of the program.  In general, variable names cannot

  1. contain spaces; for example, Birth Date is not a valid variable name; instead use birthDate or birth_date;
  2. start with a number; they need to start with a letter; for example, 6Keys is not a valid variable;
  3. contain a mathematical operator or certain punctuation characters; the underscore character is generally allowed;
  4. be a “reserved word” or “key word” in the language (such as for or while).

Naming Conventions

In addition to the rules imposed by programming languages, programmers generally follow conventions or guidelines, which may be dictated by the teacher, project, or company for which they work.  Some of these conventions include:

  1. using camel case to distinguish separate words in a variable name; the first word is in lower case and subsequence words are capitalized, like the humps in a camel (e.g., birthDate);
  2. using underscores to separate words in a variable name (e.g., birth_date);
  3. using all upper case for constants (“variables that don’t vary”); for example, INITIALIZE_SIZE or MAX_AGE.

In any case, it is also important that conventions are followed consistently.  For example, an organization would choose either convention (1) or (2) above, not use camel case sometimes and underscores other times.

Example: Creating meaningful and correct variable names

The table below shows several values that a program might need to store. This exercise may seem trivial, but many students will attempt to name all of their variables using a single character. It is important to keep in mind that part of teaching students to program is modeling the best practices used by professional developers when possible.

Description of information to be stored Incorrect variable name Problem Correct variable name
First name First Name Space between words firstName
Date of birth D-O-B Uses a mathematical operator birthDate
Six keys to success 6Keys Starts with a number keys
Address My_Home_Address_in_Indiana Too long homeAddress