Sunday, February 21, 2016

Variable Coding Guidelines

One thing that separates good programmers from great programmers is the way great programmers use variables in their code. Great programmers:
  • Use clear and concise variable names. One letter variables names are acceptable when used in conventional ways recognized by everyone, like loop indices, but almost nowhere else. Variable names should use full words either in camel case (int maxTreeDepth;) or separated by underscores (int max_tree_depth;).
  •  Declare variables as close to where they are used as possible, and within the smallest scope possible. This has a number of benefits:
    • Variable "live time" is reduced. Live time can be thought of as the space between where a variable is declared, and the time it is used. Keeping this space small reduces the chance that a variable will be modified in an unexpected way, perhaps by a future maintenance programmer, before your code uses it.
    • It makes refactoring a large function into a number of smaller functions easy. If all your variables are declared at the top of the function you are refactoring, you will need to extract the variables required by each new, smaller, function one by one. If the variables are declared immediately before they are used, the refactor becomes a simple copy and paste operation. 
  • Do not reuse variables. There are some exceptions to use rule, but in general, a variable's name should be so specific that it would not make sense to reuse it for another purpose within the same scope.
  • Have empathy for people who will be reading their code in the future. I read a lot of code where programmers go to great lengths to use tiny variable names and obscure abbreviations. I think there are two possible causes for this type of programming:
    • Sheer laziness. Many stubborn programmers refuse to learn how to use modern IDEs which are capable of doing newfangled things like auto-completing variable names. As a result, these types of programmers want variable names to be as small as possible, so they do not have to type as much as if they were using good variable names.
    • Nerdy chest-thumping. Some programmers are capable of keeping all of the details of a complicated algorithm in their head using nothing but terse 1-5 character variable names. As far as I am concerned, there are only two possible explanations for this type of design. Either you don't care about the people who are going to be reading and maintaining your code in the future, or you are insecure and you want those reading the code to be impressed with how few characters your algorithm required.

No comments:

Post a Comment