Monday, July 7, 2008

Five rules of variable naming

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 capitalize 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.

Quoted.

1 comment:

  1. Ok, I don't agree with item #1.
    Not all developers use an intelligent IDE, Linux is completely written using command line editors e.g. emacs and vi.
    I usually prefer using meaningful and short names, as short as you can, but not cryptic. I prefer the GNU/UNIX/C naming.
    For example Java's UIManager.getCrossPlatformLookAndFeelClassName()
    is that a good name?

    ReplyDelete