Followers

Wednesday, July 30, 2008

5 rules of variable naming.

When I was at uni some 10 years back now, I remember one of my lecturers telling me not to make variable names too long because you would get "pain in your fingers".

Well, rule #1 goes against that advice:

1. Make your variable names long and descriptive
Visual Studio has IntelliSense, Eclipse has its own code completion, and I'm sure whatever IDE you're using can finish your variable names off for you, too. Using long names prevents the ambiguity of short or cryptic names.

2. Put units in your variable names
If you are writing an engineering application you are going to be using variables with units. Embed the unit name in the variable, for example, distanceInMM.

3. If you are using Camel Case, don't capitalise commonly hyphened, or combined words.
Let me explain.

Callback is normally spelt as one word. So, pretty please, don't call your variable callBack.

4. Never, ever use the variable name temp. The only perfectly valid exception to this rule, is when you're writing a swap function.

5. int i is perfectly valid in a small loop. I've met programmers who would crucify me for saying this, but when your loop is half a dozen lines of code long or less, int i is perfectly valid as a loop counter. It's so widely used, it's almost expected.

Original here

No comments: