Re: Tip of the week - comment your code!
- Posted by DerekParnell (admin) Oct 04, 2010
- 966 views
Comment your code profusely ...
The true art of commenting is to explain why your code looks like it does. Looking at the code itself can mostly tell you what its doing but very often you have little idea about why its doing it.
I really hate seeing comments like this ...
wcntr += 1 -- add to counter
Duh!!!
Maybe something more along the lines of ...
-- Keep track of how many widgets we have now. wcntr += 1
The other important aspect is getting the right ratio of comments to lines-of-code. I try to see code blocks at two levels, similar in concept to paragraphs and sentences. A code sentence is usually a discrete block of code from one to six or seven lines. The code sentence is a block of code that does one logical micro-task. Usually it has only one branching construct at most in it. When you get one or more code sentences together that together perform a task or function point, you have a code paragraph. I feel that most (but not all) sentences need to be explained in their comments and a separate comment should explain what the paragraph is trying to achieve.
Ideally, you should be able to get to the point where you can take out the source code from the program and then get someone else to re-write the application using just the remaining comments.