Alex Rivera | Logout

What are your "hard rules" about commenting your code?

Asked 2008-09-27T02:58:29.543
11

I have seen the other questions but I am still not satisfied with the way this subject is covered.

I would like to extract a distiled list of things to check on comments at a code inspection.

I am sure people will say things that will just cancel each other. But hey, maybe we can build a list for each camp. For those who don't comment at all the list will just be very short :)

Edit
Report

2 Answers

36

I have one simple rule about commenting: Your code should tell the story of what you are doing; your comments should tell the story of why you are doing it.

This way, I make sure that whoever inherits my code will be able to understand the intent behind the code.

answered 2008-09-27T03:19:22.177
1

I create a comment block at the beginning of my code, listing the purpose of the program, the date it was created, any license/copyright info (like GPL), and the version history.

I often comment my imports if it's not obvious why they are being imported, especially if the overall program doesn't appear to need the imports.

I add a docstring to each class, method, or function, describing what the purpose of that block is and any additional information I think is necessary.

I usually have a demarcation line for sections that are related, e.g. widget creation, variables, etc. Since I use SPE for my programming environment, it automatically highlights these sections, making navigation easier.

I add TODO comments as reminders while I'm coding. It's a good way to remind myself to refactor the code once it's verified to work correctly.

Finally, I comment individual lines that may need some clarification or otherwise need some metadata for myself in the future or other programmers.

Personally, I hate looking at code and trying to figure out what it's supposed to do. If someone could just write a simple sentence to explain it, life is easier. Self-documenting code is a misnomer, in my book.

answered 2008-09-27T06:51:52.853

Your Answer