Comments, choosing names and refactoring

Over at Teaching Students to Comment Part 1, AlfredTh blogs about the importance of comments and the technique of writing comments first and implementing the code afterwards.

In my experience, writing comments first and then implementing each comment leads to clear, maintainable and well-factored code. I first tried this after reading about it in Code Complete, Steve McConnell's excellent book. I believed he used the term PDL for this, but as something way less from than what you might read about elsewhere.

Now, a separate consideration that might have helped in Alfred's sample is identifier naming - you don't mind if I call you Alfred, do you? When dealing with variables that have a well-known unit that might be confused with something else, I make sure that the variable names, parameter names, and even function names clearly indicate what I'm talking about. DrawArc(some_stuff_t some_stuff, float angleRadians) is not too bad (ignore the first argument).

Even better, make things clear in the function name, so people don't have to look up parameter names (nothing can save you when you're using primitives). The following snipet speaks volumes, I think.

TimeSpan span1 = new TimeSpan(5);
TimeSpan span2 = TimeSpan.FromSeconds(5);

And, in closing my ramble du jour and with a nod towards the refactoring crowd, I was pretty surprised at fist when I found that I ended up *removing* most of the comments I had written when I first started commenting before implementing. The stages of coding would normally go like this:

Stage 1
void upload_file(const char* file_name)
{
// Read network configuration from settings file.

  // Connect to server.
  // Upload the file to the server.
  // Disconnect from server.
  // Display success message.
}

Stage 2
void upload_file(const char* file_name)
{
// Read network configuration from settings file.
/* lotsa code */

  // Connect to server.
/* lotsa code */

  // Upload the file to the server.
/* lotsa code */

  // Disconnect from server.
/* lotsa code */

  // Display success message.
/* very short code */
}

At this point, I realized that a lot of the stuff I had written made sense in isolation, and so I ended up removing most of the comment and factoring the code away.

void upload_file(const char* file_name)
{
net_config n;
connection c;

  read_net_config_from_setting(&n);
  connect_to_server(&n, &c);
  upload_file(c, file_name);
  disconnect_from_server(&c);
  // Display success message.
/* very short code */
}

And so... very few comments in my function bodies. Function headers are another matter, however, as those are written for a different audience - people trying to understand how to use the function rather than how it works. But that's a good topic for another day, and in any case I want to read what Alfred might have in store for us in Part 2.