Naming Variables: Rules and Best Practices
If you want to write clear, easy-to-follow, and easy-to-debug scripts (and who doesn't?), you can go a long way toward that goal by giving careful thought to the names you use for your variables. This section helps by running through the rules you need to follow and by giving you some tips and considerations for creating good variable names.
Rules for Naming Variables
The first character must be a letter or an underscore (_). You can't use a number as the first character.
The rest of the variable name can include any letter, any number, or the underscore. You can't use any other characters, including spaces, symbols, and punctuation marks.
There's no limit to the length of the variable name.
Ideas for Good Variable Names
The process of declaring a variable doesn't take much thought, but that doesn't mean you should just type in any old variable name that comes to mind. Take a few extra seconds to come up with a good name by following these guidelines:
Make your names descriptive. Sure, using names that are just a few characters long makes them easier to type, but I guarantee you that you won't remember what the variables represent when you look at the script down the road. If you want a variable to represent a user's name, use User_Name or UserName instead of un or usrnm.
Although short, cryptic variable names are to be shunned in favor of longer, descriptive names, that doesn't mean you should be using entire sentences. Extremely long names are inefficient because they take so long to type, and they're dangerous because the longer the name, the more likely you are to make a typo. Names of 2 to 4 words and 8 to 20 characters should be all you need.
Although it's best to avoid single-letter variable names, such short names are accepted in some places, such as when constructing loops. See Chapter 7, "Controlling Your Code II: Looping."