2.5: Naming Concepts
- Page ID
Naming variables is a big deal. Anyone looking at your code should be able to understand what the variable is by the name you give it.
The C++ compiler has a few naming rules:
- Names cannot start with a number (for example, 9to5).
- Names that contain a double underscore (such as my__name) are reserved and shall not be used.
- Names that begin with an underscore (such as _name or _Name) are reserved and shall not be used.
Below are a few examples of good and bad naming.
|GOOD NAMES||BAD NAMES|
Distinguishes two objects
Conveys global status
Too general, unknown
Easy to read
What does it mean??!!
|sourceFile , destinationFile
|srcFile , dstFile
The idea is to use names that make sense, that mean something in the context of the code, and that someone looking at your code doesn't have to spend an hour tracing things back through the code to figure it out.
One of the common places we see problems is in loops. Programmers love to use things like i or x as counting variables in loops. Don't be lazy, name it something simple like 'counter', or 'loopCount' - yes, it takes a bit more typing, but its easier to read and to understand.
If the your code reqiures the use of some mathematical or scientific constant it is best to define that variable as a constant instead of littering your code with some odd number. It would be confusing to see the number 299792458 scattered throughout your code, but if you were to declare a meaningful name
const int speedOfLight = 299792458; // Speed of light in meters per second
it makes for much more readable code by using the variable name in your code, instead of scattering some odd number all over your code.
What Case Should I Use?
This is one of those questions that will get you responses about how you should only do it one way and never the other, and other people will tell you do it the other way and never the one way.
We are talking about what is known as snake case and camel case.
- in snake case words are separated by an underscore: first_name, last_name
- in camel case you use lowercase on the first word, and upper case on the first letter of all other words: firstName, lastName
As has been stated before, when you are writing code in the real world, whoever is paying you will usually have rules about how you will write your code. It is advisable that you follow their requirements if you enjoy your job.
What should I do?
For naming in this class:
- All naming requirements for C++ must be followed
- Camel case is required for all variable, function and method names.
- Meaningful names are required - no use of single letter variable names unless it is a well known mathematical usage (i.e. c2 = a2 + b2 you could use variables named a, b, and c in this case)