Skip navigation

Sign up | Lost password? | Help

Hello World

Practical programming... and stuff...

Verbose programming

Do you use variable names like $a, $b or maybe $foo or $bar in your code?

Stop using them, it's bad practice.


I've used similar variable names such as those for a long time myself, but I've been moving away from them for a while now.

But why is it bad?

If you think about the english language... why are the words this long? Wh ar w n wr l t?

Catch my drift?


If you use variable names which are short, it might make your code look shorter or a bit cleaner, but with a cost on understanding. It's much easier to understand what variable photoManager does than variable ph. You probably aren't naming your functions with too short names either, why should you be naming your variables like that?

If you think about languages like Visual Basic which are naturally more verbose than PHP or C with constructs ending usually in end construct-name and not { } you can immediately see how much easier it is to comprehend the code, especially for beginner programmers.


Using descriptive variable names also leads to self documenting code, meaning you won't need to comment as much because reading your code should already tell you what's going on.

This topic is discussed at lengths in the book Code Complete which I highly recommend.

There is one use for one letter variable names that I think is okay, though. As counters in loops. If your counter variable is just the index number of an array or something, use i, j, k or whatever you want. It's obvious what it is and what it does in context like that.

Running both PHP4 and PHP5Debugging PHP

Comments

djahandarie 20. August 2007, 10:15

Hypocrite. P:

zomg 20. August 2007, 14:52

Everyone is. =)

This is a guideline, not an absolute rule. I try to follow these in anything slightly bigger.

darylducharme 30. August 2007, 18:48

Absolutely. I finished reading through Code Complete ( vol. 2 ) a month or two ago and that was one of the points that I have been able to most easily remember and use consistantly. That book should be required reading for anybody who wants to code better. I first got the book at the library and it was so good, I bought it so that I could have it as a reference.

zomg 1. September 2007, 12:26

Indeed, it's a good book.

There's one situation where I agree with using shorter variable names: mostly in loops or when the assignment of the short name is obvious and visible. Ie. inside a few row radius from where it's used. This can let you use shorter and cleaner syntax, for example in HTML templates where extra stuff can easily make for more confusing lines.

How to use Quote function:

  1. Select some text
  2. Click on the Quote link

Write a comment

Comment
(BBcode and HTML is turned off for anonymous user comments.)

If you can't read the words, press the small reload icon.


Smilies