I try to find out not according to semantics but weight. I mean, should I take care when set a long name to a variable?
Asked
Active
Viewed 7,698 times
2 Answers
5
The comments to the original question have the best answers:
- The length that provides the most readability and clarity of purpose. – Robert Harvey
- As short as possible. As long as necessary. – CodesInChaos
Bryan Oakley
- 25,479
0
There's no set length which can be said to be the ideal length for a variable name (in Java or in any other language, pretty much). There are, however guidelines you can use when deciding:
- The most important thing about the variable name is that it clearly shows the purpose of the variable, and that it is clearly readable, as mentioned by @RobertHarvey. Remember that you're not writing read-only code, and that some poor sod is going to have to go through that code in a few months' time in order to do some maintenance. If you're unlucky, the poor sod in question might even be you :P
- It's mostly included in point 1, but avoid ambiguous names, or names that are too similar to other variable/class/function names already in use.
- Follow language conventions. In Java, that generally means naming variables in camelCase. In some cases (not sure about Java) that might mean that naming a loop index i is perfectly acceptable, for example, despite the fact that it's not all that informative a name.
- All else being the same, prefer shorter names, but only as long as it doesn't impact readability. If you find yourself trying to contort variable names in order to shave a character or two off, please stop and give a bit of thought to said poor sod who's gonna have to read the code in a few months' time.
Iker
- 865