Tuesday, October 10, 2006

Commenting Code

I was recently asked my opinion on commenting code and if there were any standards that I follow. I have been a big believer in commenting code as long as I've been programming. I used to add comments to my own Basic code that I wrote on the Commodore 64 even. It's always been strange to me to go into a very complex piece of code and not see any comments. I would pick it apart and come out with a dialog that commonly goes like this.

Me: "This code is doing thing A exactly.
Other: That code is supposed to be doing A and B.
Me: Ok, but I didn't know that. I can only tell you what the code tells me. It does thing A.
Other: Why wasn't this caught sooner.

When things like this happen it's always the same. Even if I've been working on a piece of code for a long time, I cannot notice and change the problem in a function like this. I can possibly refactor the code to make it do A more efficiently or easier, but I can't make it do both A and B because there are no comments.

I believe that there should be a comment stating what the purpose of something is. Especially in the agile process where the requirements are small pieces that generally do not generate much in the way of design. Having a comment in the code that says what the process is supposed to do, is a good way to help other developers with understanding the code.

Unit testing is a good "What the code does" documentation, but it's not used everywhere. Having good unit tests could prevent the need for needing the documentation, however, unit tests are not written in clear English. When I write unit tests, I like to document the "What" in my unit test class. However, I'm not consistent enough with my unit testing.

Ultimately, having documented what is supposed to happen somewhere is very important. It allows others later to come in and see if the code is working properly.

No comments: