Friday, August 03, 2007

Why do we need comments?

Yesterday I was reviewing some java code and it was more or less similar to the one given below.



//Assign i with the value 0

i=0;

//increments the variable i

i++;



Here each and every line is accompanied by some sort of comments. Some programmers believe that good programming practice is to write as much as comments you can. In the case of programming in machine language and or assembly language this is required and will be helpful to understand the program. But will it make any sense in the case of contemporary high level languages?

I certainly believe no. All the modern programming languages are English like and human readable. So if the code itself is meaningful, what is the need of repeating it again? I believe that the code itself is the best document for it. The benefits of practicing this is multi fold. Apart from saving a lots of human effort, the code looks clean and compact. This gives a macro picture of the logic at a glance.

So does it mean commenting a program is that bad? Not at all.
Comments are good aid for the reader if it is given to a set of cohesive statements. This also helps to visually separate such blocks like a paragraph in an essay. Languages like java and c# allows document style comments and this will be highly helpfull to generate the API document. It is good practice to document all the classes and methods with API document style comments.

A well written code is like a poem where it can be appreciated even over the phone. So you can do a simple telephone test to find out the readability of your code. If the listener is able to understand the logic then obviously you have passed the test!

No comments: