Having had a fairly long day, I was thinking about going to bed “early” (before 2am) when I decided that I just should check out Planet CDOT before sleeping. Although I don’t blog as much as I should, once in a while some things make me want to blog to put in my thoughts on the matter. Thus, my quick 10 minute pre-bedtime blog browsing is turning into a much longer pre-bedtime blog writting session.
Dave Humphrey blogged about comments being possibly harmful today. Well that caught my attention because I know that I am one of those teachers that thinks that code should have comments in them. However, having read Dave’s blog, I can’t say that I disagree with him. I too have been led astray by comments left in some source file. Sooo… to procrastinate on going to bed I figured I’d write what I think I would prefer for comments because I think there is a time and a place for them but the comments written should be meaningful and have semantic knowledge.
My thoughts are simply as follows… I hate comments that repeat code. This is actually something that I have observed students do and it is a pet peeve of mine. Comments should say something that code does not or possibly cannot say. If your code is so complex that no one can possibly understand it without a comment… perhaps it is time to consider rewriting it so that it is understandable.
For example, I ask my students to provide a data dictionary… that is variables should have comments stating what they are used for. And once in a while I get comments like:
double weight; //a double holding the weight
err…???? What I want to know at this point is why on earth this person is coding in english inside the comment… If I wanted to see code in English I would use COBOL (/shudders). Repeating your code in your comment is not useful. A comment should provide information that cannot be gleaned from your code… for example:
double weight; //the weight of the car in kg
I don’t need to know that its a double or that its name is weight because I’m fluent in the programming language. it would be like saying:
/*this loop runs 10 times*/
really? nah… it cannot be…how did I ever manage without that comment (/sarcasm)
The other situation where I think it is useful to actually have a comment is in the function description. That is, when you code a function you should be able to state what it does (not how, just what), what its expected return values are and what argument it expects. While how you implement that function may change, what it does should not change nearly as readily. Thus, the focus of your comments really should be on a very high level what (and even sometimes a short why) but forget about the how .
Anyhow… my 10 min. blog reading session is now way longer than 10 min. Time to sleep.