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?

  • 4
    The length that provides the most readability and clarity of purpose. – Robert Harvey Aug 6 '16 at 5:36
  • 11
    Exactly 27 characters. – user22815 Aug 6 '16 at 5:41
  • 1
    @Chip That's why programming takes so long. It is pretty difficult to find a meaningful name for any variable when the requirement is the length must be exactly 27 characters. But oh boy is it worth it. – Andy Aug 6 '16 at 6:58
  • 4
    As short as possible. As long as necessary. – CodesInChaos Aug 6 '16 at 9:08
  • 1
    Possible duplicate of Is there an excuse for short variable names? – Martin Schröder Aug 6 '16 at 13:51

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
| improve this answer | |

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:

  1. 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
  2. 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.
  3. 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.
  4. 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.
| improve this answer | |
  • It is ok for coding conventions, what I'd like to know is what happens in the JVM. I mean, is there a high level cost for declaring long variables names? – B. Alpízar Aug 8 '16 at 1:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.