Thursday, June 15, 2006

Why comments in code are useful ...

Everyone who is a programmer knows that good coding isn't just writing code that has very few problems, is efficient, does what it's supposed to, requires little maintenance and is easily extensible. This means that it is not just about using correct syntax and the latest and greatest algorithms and implementing them correctly. It is about telling oneself and others why something was implemented a certain way. Yeah, you may already guess it and you are right. I am talking about comments in code. I know, I know, you may say: "I bet Joerg has sometimes delivered less than perfectly commented code". And you are right, but I try to always do it when appropriate. Hell, I don't need someone to tell me something like this:

void incrFunc( int& i ){
i++; // adding one to i
}

That's dumb, don't state the obvious. But when you chose a certain algorithm or use something that is non-standard, write a line or two about it and add documentation so that people that will have to pick up your code know what the hell you were thinking. Why am I writing about this? Well, I am currently working on a project that is about integrating something cool and new into an older codebase. And this includes using code others have written. It's amazing when you trying to code towards certain APIs what kind of surprises you sometimes see. And you don't see them by reading the code, you learn through painful and time-consuming debugging. Here is an example. Consider the case where you have larger buffer and you have to mark certain regions in the buffer to identify subsections. One way to do this would be through a struct like this:

struct section {
int start;
int end;
};

Now, for me, the intuitive thing would be to assume that start denotes the byte offset of the first byte of the section and end would denote the offset of last byte of the section. Well, I came across some code where end pointed to the first byte after the section. Why? Well, no comment or anything in the code. Thankfully, the programmer was still there and I could ask. And even though he had a reason for doing so (he wanted to be able to express section of length zero [don't ask me why], and ...well...laziness), a comment would have avoided a bunch of confusion. Even better, don't name it end but length and there is no ambiguity at all. What's even worse is that when I asked the programmer about it he did not know/remember why he did that. And this is where useful comments come in again. They are not just good for others, they help you as well. And believe it or not, the code that you write will be seen by more people than you might think. So use smart comments but don't litter the code, nobody wants to read source code files that are 4000 lines or longer. This is another one of these things that people shouldn't do but I will leave that to another post.

No comments: