Lets say i have a variable that contains the number of search engine names in a file, what would you name it?
The first name describes what the variable contains precisely, but isn't it too long?, any advice for choosing variable names? especially how to shorten a name that is too long or what kind of abbreviations to use?
Having really long variable names will muddle up your code's readability, so you want to avoid those. But on the other end of the spectrum, you want to avoid ultra-short names or acronyms like "n" or "ne." Short, cryptic names like these will cause someone trying to read your code to tear their hair out.
By convention, variable names start with a lower case character. The easiest way to make sure you are not adding lines longer than 80 characters wide is to always work inside a window that is exactly 80 characters wide.
As per standards, longer descriptive names are advised to make it more readable and maintainable on longer term. If you use very short naming e.g. a variable as a , you will forget yourself, what that variable is meant for after sometime. This becomes more problematic in bigger programs.
Variable names in C++ can range from 1 to 255 characters. All variable names must begin with a letter of the alphabet or an underscore(_).
How about numEngineNames
?
Choosing variable names is more art than science. You want something that doesn't take an epoch to type, but long enough to be expressive. It's a subjective balance.
Ask yourself, if someone were looking at the variable name for the first time, is it reasonably likely that person will understand its purpose?
A name is too long when there exists a shorter name that equally conveys the purpose of the variable.
I think engineCount
would be fine here. The number of engine names is presumably equal to the number of engines.
See JaredPar's post.
It depends on the scope of the variable. A local variable in a short function is usually not worth a 'perfect name', just call it engine_count
or something like that. Usually the meaning will be easy to spot, if not a comment might be better than a two-line variable name.
Variables of wider scope – i.e. global variables (if they are really necessary!), member variables – deserve IMHO a name that is almost self documentary. Of course looking up the original declaration is not difficult and most IDE do it automatically, but the identifier of the variable should not be meaningless (i.e. number
or count
).
Of course, all this depends a lot on your personal coding style and the conventions at your work place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With