views:

335

answers:

11

I've always hated comments that fill half the screen with asterisks just to tell you that the function returns a string, I never read those comments.

However, I do read comments that describe why something is done and how it's done (usually the single line comments in the code); those come in really handy when trying to understand someone else's code.

But when it comes to writing comments, I don't write that, rather, I use comments only when writing algorithms in programming contests, I'd think of how the algorithm will do what it does then I'd write each one in a comment, then write the code that corresponds to that comment.

An example would be:

//loop though all the names from n to j - 1

Other than that I can't imagine why anyone would waste valuable time writing comments when he could be writing code.

Am I right or wrong? Am I missing something? What other good use cases of comments am I not aware of?

+16  A: 

Comments should express why you are doing something not what you are doing

JaredPar
+1: Anyone can read the code to see *what* you're doing. But **why** can be a complete mystery without some explanation.
S.Lott
Yawn This tired cliche gets trotted out every time. Try reading a big chunk of C or assembler without any comments and see if you can work out what it is doing. Comments are needed to cover both why and what.
anon
It's also harder for others to know whether some behavior of your function was intentional or not. Without comments, others can 'fix' code that isn't broken, or they may consider it too risky to fix something that looks wrong, and really is.
Scott Smith
Should add "if not obvious" to the why. I've seen far too many "Incrementing i so I can keep count" comments
Pestilence
@Neil I think the point about 'not documenting the what' is for comments that say: "var++; // increment var by 1". Only helpful to someone completely unfamiliar with the language. Better to say something like "var is zero-based, but array is one based"...
Scott Smith
@Scott - I shudder at your zero-based arrays.
Chris Lutz
FWIW, I've heard the terms *Strategic* and *Tactical* used to refer to the high-level *why* and line-by-line *what* comments.
Scott Smith
@Neil Butterworth: The only time I've had trouble with **what** the code does is when someone is really doing mind-bending code-golf. Other than that, the **what** has always seemed pretty clear. Maybe I've just been lucky for the past few decades.
S.Lott
@S.Lott Maybe you are a code god, but I need all the help I can get. If I come across 10 lines of assembler with a comment that says "find length of string" I'm happy, if there is no comment I'm not.
anon
"Why" can also be expanded to explain "why this method and not any other one that may fit"
Peter M
@Scott // Here be dragons
Helper Method
@Neil Butterworth: "10 lines of assembler with a comment that says "find length of string"" -- that's an excellent example of a **why** comment.
S.Lott
@S.Lott Surely not. It says WHAT the code does. A WHY comment would say why this particular algorithm was used, or why it was used at this point in the program.
anon
@Neil Butterworth: I agree with you for the most part. You should not tell someone via comment what a for-loop does or that you are about to call a method. However, you may need to say WHAT your code does to satisfy a business rule; it may not be obvious and developers are not all subject matter experts.
Phil
@Phil I would say business rules are WHY comments - "regulators say we can't lend if there are more than three risk factors", at the top of a OKToLend() function, for example.
anon
So /* I put this function here because the program didn't work without it */ is preferred over /* this function thinks it computes the length of a string */. Ok, gotcha. My coworkers are gonna love me now!
Tim Schaeffer
+6  A: 

It's an old adage, but a good metric to use is:

Comment why you're doing something, not how you're doing it.

Saying "loop through all the names from n to j-1" should be immediately clear to even a novice programmer from the code alone. Giving the reason why you're doing that can help with readability.

Ryan Brunner
So I should comment why I'm adding the comment? Turtles, turtles, turtles, ...
Tim Schaeffer
@TIm LOL No, you should comment code. Common sense, common sense, common sense.
JeremyDWill
+1  A: 

It's not a bad idea to record what you think your code should be achieving (especially if the code is non-intuitive, if you want to keep comments down to a minimum) so that someone reading it a later date, has an easier time when debugging/bugfixing. Although one of the most frustrating things to encounter in reading someone else's code is cases where the code has been updated, but not the comments....

davek
If the code is unintuitive, I'd comment what and how at the important and confusing parts, just so that maintainers have an understanding of what's going on. I'd also comment why, so that they know what to expect, but that's one case where "how" is important to document IMHO.
Chris Lutz
+5  A: 

If you use something like Doxygen, you can fully document your return types, arguments, etc. and generate a nice "source code manual." I often do this for clients so that the team that inherits my code isn't entirely lost (or forced to review every header).

Documentation blocks are often overdone, especially is strongly typed languages. It makes a lot more sense to be verbose with something like Python or PHP than C++ or Java. That said, it's still nice to do for methods & members that aren't self explanatory (not named update, for instance).

I've been saved many hours of thinking, simply by commenting what I'd want to tell myself if I were reading my code for the first time. More narrative and less observation. Comments should not only help others, but yourself as well... especially if you haven't touched it in five years. I have some ten year old Perl that I wrote and I still don't know what it does anymore.

Something very dirty, that I've done in PHP & Python, is use reflection to retrieve comment blocks and label elements in the user interface. It's a use case, albeit nasty.

If using a bug tracker, I'll also drop the bug ID near my changes, so that I have a reference back to the tracker. This is in addition to a brief description of the change (inline change logs).

I also violate the "only comment why not what" rule when I'm doing something that my colleagues rarely see... or when subtlety is important. For instance:


for (int i = 50; i--; ) cout << i; // looping from 49..0 in reverse
for (int i = 50; --i; ) cout << i; // looping from 49..1 in reverse
Pestilence
I like the part about what you would want to know if you were looking at it for the first time or first time in a long time. And in my experience this also tends toward the "why" more than the "what".
GalacticCowboy
A: 

I've always hated comments that fill half the screen with asterisks just to tell you that the function returns a string, I never read those comments.

Some comments in that vein, not usually with formatting that extreme, actually exist to help tools like JavaDoc and Doxygen generate documentation for your code. This, I think, is a good form of comment, because it has both a human- and machine-readable format for documentation (so the machine can translate it to other, more useful formats like HTML), puts the documentation close to the code that it documents (so that if the code changes, the documentation is more likely to be updated to reflect these changes), and generally gives a good (and immediate) explanation to someone new to a large codebase of why a particular function exists.

Otherwise, I agree with everything else that's been stated. Comment why, and only comment when it's not obvious. Other than Doxygen comments, my code generally has very few comments.

Chris Lutz
Leo Jweda
@Laith - I hate any comment-documentation format that uses embedded XML or HTML for formatting, but normally Doxygen isn't too bad. That particular snippet has a high comment-to-code ratio, but it also showcases the hated `i++; // post-increment i by 1` style of commenting, so ignore that. Also, I predominantly use C, so most of that code would be slightly more verbose for my average use-case.
Chris Lutz
+2  A: 

Comment everything that you think is not straightforward and you won't be able to understand the next time you see your code.

Bozho
This is actually one of the ways I comment in my own code. I sometimes have to do fancy tricks due to quirks and others may not automatically catch these- hence, I write them in comments.
Phil
A: 

Another type of comment that is generally useless is:

// Commented out by Lumpy Cheetosian on 1/17/2009

...uh, OK, the source control system would have told me that. What it won't tell me is WHY Lumpy commented out this seemingly necessary piece of code. Since Lumpy is located in Elbonia, I won't be able to find out until Monday when they all return from the Snerkrumph holiday festival.

Consider your audience, and keep the noise level down. If your comments include too much irrelevant crap, developers will just ignore them in practice.

BTW: Javadoc (or Doxygen, or equiv.) is a Good Thing(tm), IMHO.

Scott Smith
I gotta say, I love the names you came up with.
Leo Jweda
A: 

I also use comments to document where a specific requirement came from. That way the developer later can look at the requirement that caused the code to be like it was and, if the new requirement conflicts with the other requirment get that resolved before breaking an existing process. Where I work requirments can often come from different groups of people who may not be aware of other requirements then system must meet. We also get frequently asked why we are doing a certain thing a certain way for a particular client and it helps to be able to research to know what requests in our tracking system caused the code to be the way it is. This can also be done on saving the code in the source contol system, but I consider those notes to be comments as well.

HLGEM
+4  A: 

I use comments in the following situations:

  1. High-level API documentation comments, i.e. what is this class or function for?
  2. Commenting the "why".
  3. A short, high-level summary of what a much longer block of code does. The key word here is summary. If someone wants more detail, the code should be clear enough that they can get it from the code. The point here is to make it easy for someone browsing the code to figure out where some piece of logic is without having to wade through the details of how it's performed. Ideally these cases should be factored out into separate functions instead, but sometimes it's just not do-able because the function would have 15 parameters and/or not be nameable.
  4. Pointing out subtleties that are visible from reading the code if you're really paying attention, but don't stand out as much as they should given their importance.
  5. When I have a good reason why I need to do something in a hackish way (performance, etc.) and can't write the code more clearly instead of using a comment.
dsimcha
A: 

Reminds me of

Real programmers don't write documentation

Helper Method
A: 

I wrote this comment a while ago, and it's saved me hours since:

// NOTE: the close-bracket above is NOT the class Items.
// There are multiple classes in this file.
// I've already wasted lots of time wondering,
// "why does this new method I added at the end of the class not exist?".
Coronatus