Getting students (actually just about any programmer) to write comments is an uphill battle. I tried to convince my students of the value of comments by something from my own experience.
I had written a graphics program back in college many years ago. A few years later (OK about 20) I decided to write the same program again. This time I was programming in Visual Basic. FORTRAN seems not to be so easily available any more. I remembered most of the program and knew I could figure the rest out as I went alone. The program was supposed to draw geometric shapes but when I ran it lines went everywhere but where they were supposed to go. I stared at the image on the screen and realized that I’d had a similar problem when I had written the original program. What I could not remember was how I’d fixed it.
Believe it or not I still had a copy of the original code. It was on punch cards (yeah, I go back that far) and I was able to find it in a box that my wife thought I had thrown out. Fortunately I had written comments for the code. I quickly found the problem. I was passing angle information in degrees rather than in radians. A comment explaining the parameter for a function call made this clear. A quick change and the program was working just great.
That’s a good story for justifying commenting code that is non-obvious or to explain something that was not easy to understand. It’s also a good example of why interfaces to methods, modules, classes and the like should be commented. But we all know that those kinds of comments are still too rare.
I recently read a blog entry by Justin Creasy, CTO of Immerge Technologies on the subject of commenting. I recommend Justin’s version but the short version is that his team writes to comments before the code. In short they build the outline of the program using comments during the architecture and design phase of development. This has several advantages. One is that it aids the planning process. Another is that the comments are already there when the code is written. The trick of course is keeping to comments updated as the program changes.