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, your code is not so great that it doesn’t need comments

Posted in Software Development by Dan

Code-commenting is so basic and so universal that every programmer, regardless of the language that they practise, thinks that they know all there is to know and that their way is the only sensible approach (I am no different in this respect). I guess that’s why there are so many blog postings offering advice on commenting (you can add this one to the list).

Even the elite of programmer bloggers are having their say. Steve Yegge covered it and, more recently, so did Jeff Attwood. Jeff’s basic advice, that you wouldn’t need so many comments if you wrote the code to be more self-explanatory, is sound but the idea that we should be aiming for some kind of perfect code that has no need for any comments is dangerous.

It’s not a sensible goal for beginners and inexperienced developers. Tell them that they should write good code without any comments and they will deliver on the second part but struggle with the first. Even among experienced developers, assuming for a moment that it is possible to write perfect code that doesn’t require comments, there will be far fewer who are capable of this than there are who think that they are.

The other arguments against commenting are even weaker in my opinion. Yes, poor comments are …well… poor. So don’t write poor comments, write good ones. And yes, if comments become out-of-sync with the code then they are not helpful. So don’t let the comments become out-of-sync, they are part of your code and should be maintained/refactored along with the code itself.

I don’t believe that I’ve read a piece of code and thought “wow, this has far too many comments”. Unfortunately, I’ve had the opposite reaction all too often. I don’t for one moment believe that it is possible to write quality code without any comments. Take Jeff’s own example:

Here’s some code with no comments whatsoever:

r = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
System.out.println( "r = " + r );

Any idea what that bit of code does? It’s perfectly readable, but what the heck does it do?

Let’s add a comment.

// square root of n with Newton-Raphson approximation
r = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
System.out.println( "r = " + r );

That must be what I was getting at, right? Some sort of pleasant, middle-of-the-road compromise between the two polar extremes of no comments whatsoever and carefully formatted epic poems every second line of code?

Not exactly. Rather than add a comment, I’d refactor to this:

private double SquareRootApproximation(n) {
r = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
return r;
}
System.out.println( "r = " + SquareRootApproximation(r) );

I haven’t added a single comment, and yet this mysterious bit of code is now perfectly understandable.

Sorry Jeff, but that’s not “perfectly understandable”. I agree with extracting the square root code into a separate method with an appropriate name, but your second version (the one with the comment) was more informative since it mentioned which algorithm you were using (in your version, the maintainer is going to have to figure that out for themselves). Also, we’re still left with at least two poorly-named variables. We can forgive the use of n for the parameter since that’s kind of a convention but what the hell are r and t?

In my opinion, this is better:

/**
* Approximate the square root of n, to within the specified tolerance,
* using the Newton-Raphson method.

Original here
*/

private double approximateSquareRoot(double n, double tolerance)
{
double root = n / 2;
while (abs(root - (n / root)) > tolerance)
{
root = 0.5 * (root + (n / root));
}
return root;
}

Alternatively, if you don’t like the verbose comment at the top, you could either rename the method to something like newtonRaphsonSquareRoot (if you are happy for the method name to be tied to the implementation) or put an inline comment in the body explaining that this is the Newton-Raphson method. Any of the three variations will communicate useful extra information to the maintenance programmer, who can then Google “Newton-Raphson” if they want to find out more about it. Remember that code is written only once but read many times. It should be tailored for the reader rather than the writer.

This is all very well, but we’re still lacking some information. Why the hell is Jeff calculating square roots in this way? Why is he not using the library function? Is it because he doesn’t like the answers it gives him? Is it for performance? Who knows?

Well-written code will often answer the “what?” and “how?” questions with few or no comments, but you often also need to answer the “why?” question too. Avi Pilosof covers this in his response to Jeff’s post. Avi argues that rather than comment the code, you should comment the business justification for writing the code that way. This may mean inserting reference to particular requirements or issue reports.

So yes, favour code that is self-explanatory, but I don’t believe that you can always achieve the necessary clarity without a few well-placed comments to aid understanding. Code that is obvious to the author today is rarely obvious to the maintainer next year (or even to the author next month).

And if you still really believe that your code does not need any comments, then I hope we never have to work together.

How I got started programming

  1. How old were you when you started programming?By the time I really got into computers around age 12 or 13 my parents old Tandy 3000 wasn’t quite up to date compared to the 386’s and 486’s most of my friends had. I really truly started coding in TI-BASIC on my TI-85. I created all sorts of games, programs and such, which I’d then trade and sell to other kids at school. Around age 16 I bought a custom built machine from a local computer shop. A Cyrix 133 with 16MB of RAM, which I soon upgraded to a Cyrix 200 with 40MB of RAM. It wasn’t long after this that I started coding IRC bots for mIRC and HTML on my Geocities website.My first true coding experience didn’t really come until I started college where I was introduced to PHP by my friend Paul Barton. It was love at first site and the rest is, as they say, history.
  2. How did you get started in programming?I really started in college, but I’m sure there was some BASIC and VB stuff for office here and there before that. My first programs were written in TI-BASIC and ASM for the TI-85.
  3. What was your first language?TI-BASIC for the TI-85 calculator is the first programming language I really sunk my teeth into. What a nightmare.
  4. What was the first real program you wrote?Depends on how you define this I suppose. The first program that I wrote that had any use to me was a program that would figure out math equations for my algebra and statistics classes that would show each step of work as it solved the equation. That’s also the first program I wrote that I made money from as there were quite a few students interested in it.
  5. What languages have you used since you started programming?I guess that depends on what you mean by “used”. I’ve written substantial lines of code in C/C++, PHP, Python, Perl, ASM, BASIC, TI-BASIC, JavaScript and BASH. I’ve also done quite a bit of work in COBOL and MFC.
  6. What was your first professional programming gig?My first paid gig was working on the website for Affordable Computers in Ann Arbor, MI. I’d say my first run at the “big show” was for Care2.com in 2000.
  7. If there is one thing you learned along the way that you would tell new developers, what would it be?Break stuff. Break everything. Poke, prod and explore. Don’t listen to people who tell you that you can’t do something or that you’re wasting your time. More practical advice is that you should learn to know and love design patterns and avoid GUI’s. I have a real problem with people who say they know SQL because they’re well versed with an ORM or a DB’s GUI. Go back and read up on relational algebra and SQL92 before you say you know SQL okay?I’ll probably get flamed for this, but I think people should learn a single environment in and out and stick with it. This might mean you learn Microsoft’s technologies in and out or Cocoa or LAMP. You simply can’t be an expert in an area of computers without picking a single environment and sticking with it. Dabble, sure, but pick a horse and learn everything you can about it.If you choose UNIX read one man page a day until you’ve read all of the GNU utilities’ man pages. You’re not a true UNIX geek unless you’ve typed man man at once point in your life.
  8. What’s the most fun you’ve ever had programming?Oh, I don’t even know where to start. Hacking on PHP3 back in my dorm room, working with Jeremy and Seth on Care2 late into the night, building eNotes’ infrastructure from the ground up and building large scale systems with Ron and Matt at Digg to name just a few.

This absurd entry was spurred on by Erik Kastner. I’m going to give him a noogie next time I see him for this. Because I hate chain posts like this I won’t be tagging anyone as it after this, but if you do carry this on please trackback this post so I can read and reminisce with you.

Original here