(Note: This is about comments in code, not the topic of blog comments which was debated recently by various bloggers.)
One of the first things they teach programmers about comments is, "Don't merely repeat in the comment what the line of code literally does." A laughable example such as the following is usually given.
x = y * y; // Set x to the square of y. |
In general I abide by this rule, but there is one exception: when I need a comment to turn a line of code into a section of code.
I use inline comments to break a block into logical sections. Taken by themselves, the comments tell a story. For example, here's a method that creates a cake, the way some people would write it:
- (xxx *)cake { // Bake in oven. xxxxx; xxxxx; xxxxx; // Add icing. xxxxx; xxxxx; return xxxxx; } |
The above code doesn't look right to me, because it looks like the "return xxxxx;" is part of the "Add icing" step when it's not. To rectify this I add a dumb comment that puts "return xxxxx;" into its own section:
- (xxx *)cake { // Bake in oven. xxxxx; xxxxx; xxxxx; // Add icing. xxxxx; xxxxx; // Return the result. return xxxxx; } |
I do something similar with methods that run through a gauntlet of reasons for possibly returning early. If they survive the gauntlet, I add a dumb "If we got this far…" comment.
- (BOOL)shouldEatIceCream { // Is the ice cream poisoned? if (xxxxx) { return NO; } // Is it my birthday? if (xxxxx) { return YES; } // If we got this far, we shouldn't eat the ice cream. return NO; } |
I try to think of something more intelligent to say in these comments, but often I don't.