views:

3712

answers:

59

What are your "favourite" overuses / misconceptions about commenting the code? Why do you sometimes think commenting is a pain? What arguments would you use to convince others that less is more at commenting in some cases?

This is the negative counterpart to How to convince people to comment their code - such that it remains a collection of answers, not a convoluted discussion. Compare also Commenting code, Do you comment your code, and What's the least useful comment you've ever seen?

How about writing one reason per answer, so the voting works on the reasons?

A: 

Writing good comments is an art just like writing good code. When too many comments obfuscate the code itself or when the comments duplicate the code then it may be time to back off a little.

mxg
"When too many comments obfuscate the code" ... then it hightime to back off!
Andre Bossard
+82  A: 

The classic way NOT to comment is:

//add 1 to count

count++;

Rename count to tell me what you are counting and I don't need a comment. Telling me what the counter is used for would be okay in a comment.

Jim C
The only time to comment WHAT something does is when it's complex, and only at the block level (perhaps comment a double or triple nested loop to explain what the loops are doing). Other than that, this type of comment is fairly useless, IMO.
Thomas Owens
Even then, you should be able to wrap the code block in a function with a descriptive name. Nested loops are a code smell. You should probably wrap the inner loop in its own function.
Patrick McElhaney
+2  A: 
KernelM
A: 

Some conventions require you to enter tons of nearly useless javadoc-tags. For instance:

/** The ID for the User. (For the format compare {@link IDGenerator}). */
private String id;

/**
 * Gets the ID for the User. (For the format compare {@link IDGenerator}).
 * @return the ID
 */
 public String getID() { return id; }

/**
 * Sets the ID of the Object. (For the format compare {@link IDGenerator}).
 * @param id the ID to set
 */
public void setId(String theId) { id = theId; }

EDIT: My point is especially that in some conventions you are enforced to comment the variable, the setter and the getter, although they are nearly identical and should be unified. This might be good practice for public APIs and Open Source Code, but is certainly overdone for internal code. For this purpose I'd suggest to leave out the @param and @return tags and just comment the getter.

hstoerr
These can be pretty important even if they seem useless to you. For example, in this case, what is an expected ID? Are there limits on length? Especially important for APIs where the person reading the doc won't see the code.
tloach
I don't understand, but do you think standardizing on a comment style is useless?
Till
Can you pass null to that method? What about an empty string? Does the value have to be unique? Does it have to begin with an alphabetic character? Or a number? Is the ID case-sensitive?.....
Jeffrey L Whitledge
Well written like that, yes is useless. But if this method will be part of th API, then some sort of information about the origin of the Id becomes very useful as Tloach, Till and Jeffrey said. But if the method is not part of the API then it should be private ( or package default )
OscarRyz
A id which is stored in a String? That needs serious clarfication...
Andre Bossard
I tried to clarify what I mean with an update of the answer. My point is that in internal code it usually seems overblown to require every single javadoc tag. In my experience developers tend to skip javadoc comments completely if you require them to be absurdly repetitive.
hstoerr
+6  A: 

Comments are sometimes used as an excuse for writing obtuse code.

By encouraging others to write less comments, it sometimes encourages them to use better names in variables, methods, etc. and use more understandable logic and flow.

Kevin Fairchild
+27  A: 

// gets the user from the session
User user = session.getAttribute("USER");
// Gets the comment from the user's comments from the comment id on the request
Comment comment = user.getComment(request.getAttribute("COMMENT_ID"));
// Adds one to comment rating
comment.rating++

JeeBee
Also adds one to your rating :)
Victor Hurdugaci
+64  A: 

Don't explain the programming language to the reader. You should assume readers know the language as well as you do (or can look things up if necessary).

For example, I once saw C++ code that looked something like this:

// This is a template.  A template allows us to specify a
// class that can be parameterized with other types.
template <class T>
class Foo {
   // ...
};

// Use 'typedef' to declare type aliases
typedef Foo<int> IntFoo;     // IntFoo instantiates Foo for 'int'
typedef Foo<char> CharFoo;   // CharFoo instantiates Foo for 'char'

Such comments make sense in a tutorial, but they don't belong in production code.

Kristopher Johnson
probably was copied and pasted from a tutorial ;)
tloach
I see code like this all the time. it's from the files we're supposed to copy and modify to create new classes (to keep consistent styling). Most people are too lazy to remove these comments.
rmeador
It can also be from a novice who still explains it in his/her head which leads to it being written down.
Asaf R
What if you know that your colleague is an idiot who can't understand the code?
Marcin
Littering the code with comments won't make the idiots any smarter.
Kristopher Johnson
+5  A: 

I'm not advocating no comments, but IMO, code should be self descriptive. If you function/method is doing more than one thing than the name implies, refactor.

levi rosol
+9  A: 

If your variable, property, and/or methods are named correctly and the code you are writing is not complex you won't really need to comment.

For example:

public bool isStackEmpty()
{
    return (this.currentStackSize <= 0);
}
Jesse Dearing
I'd want a comment there, to explain why the currentStackSize might be less than 0 ;-p
Steve Jessop
oh geez, please simplify this function toreturn this.currentStackSize <= 0;
Steven Noble
I made the edit Steven Noble suggested. I hope the original author doesn't mind.
Kristopher Johnson
Don't mind at all. However while this is a nice shortcut, one thing to try to remember is does a shortcut detract from the readability of the code? In this case I don't think it does, but it should be considered.
Jesse Dearing
I wouldn't consider it a shortcut, is the thing. How it is currently is the correct way, the original was the longer-than-needed way. Going from longer to normal isn't a shortcut, it's good progress. :P
GMan
+3  A: 

Sadly, when commenting is required for the sake of requirements, you get a bunch of "English" versions of the syntax.

The classic

// Add one
i++;

I've been required to generate 50% comments by a contract and ended up generating garbage like that. Even worse, it became part of my normal coding style. DON'T DO AS TIMMY DOES.

So my reason not to comment "Don't comment just because someone thinks there should be x% comments". That is just stupid.

Torlack
+51  A: 

Worse case I've seen is:

// Adding an extra comment to push my percentage of
// comments over the amount required
i++;

Serious horror!

Rob Wells
Heh, that is terribly but also nice since it made me chuckle!
David The Man
It's a horrible comment, but also a symptom of asinine management practices
Dana
I don't have any problem with it. :-)
Brian Knoblauch
I prefer this comment rather than "// add one to i"
Turambar
Works for me. The serious horror there is the horrible requirement which mandated the comment rather than the comment itself.
Dave Sherohman
I think that is dailywtf worthy :D
workmad3
+5  A: 

What’s the golden code/comment ratio?

Prakash
+8  A: 

I think a goal of every developer is to over time be able to write commentless code. Code that self expresses itself is beautiful code. I wouldnt go so far as to say its an excuse to write bad code, but a lot of people dont have enough experience or ability to write code that requires little or no commenting. It takes a long time, a lot of practice and experience.

Bottom line, as you get older and grow fatter, your comments should get thinner ;)

EDIT: In case others wish to downvote me for whatever reason, just to make it clear this is in general and does not go into detail about commenting complicated intentions, etc. If you disagree, put a comment so i at least know what your disagreement is. How the hell are we supposed to learn from each other with silence.

EDIT2: just figured i would add a little extreme snippet

//This check makes sure the nuclear reactor is within normal parameters
if(a < 5 && b > 8 && c == 9)
{
    ...
    ...
}

This should be refactored for 3 reasons. Reduce commenting, increase readability, reuasability

if(IsNuclearReactorWithinNormalParams(a, b, c))
{
    ...
    ...
}

bool IsNuclearReactorWithinNormalParams(int coreTemp, int stackTemp, int reloopThreshold)
{
    return coreTemp < CORE_OVERHEAT_TEMP && stackTemp > STACK_MIN_TEMP && reloopThreshhol == RELOOP_THRESHHOLD;
}

Look ma, no comments!

But even still the incoming params should also have been refactored and renamed to proper names so it is clearer. When you follow stuff such as this your commenting becomes reduced by a huge factor. ESPECIALLY when it is a mission ciritical app. Comments alone just dont cut it in mission critical apps.

mattlant
With something as important as nuclear reactor safety, I probably wouldn't be using the variable names a, b and c :) Recipe for disaster
johnc
+1  A: 
// fix for bug #6837
splines.reticulate();

Don't comment why you made a change. Put those comments in the source control system, so the comment is attached to the change itself.

Patrick McElhaney
I worked for a company that did that once. Then we changed our change control system. All of our comments were now useless since the old system had not been migrated (other than open tickets) and was not kept in service.
tloach
As long as you put a (brief) description of the bug and why the change is necessary along with the bug number, I don't see a problem with this. If I'm looking at code and don't understand why we're doing something, I don't want to go through the SCC to find out why.
Graeme Perrow
@Graeme Perrow - I think a comment why an non-obvious piece of code exists is always good, but a bug reference number requires a trip to the bug database anyway, and comments with programmer names and dates are just useless.
Jeffrey L Whitledge
If there's a long story behind why you've done something in a non-obvious way, and it's documented in a bug report (presumably because you tried the obvious way first and it caused the bug!) then a reference to the bug in a comment is a good idea. But that's not a situation that comes up every day
Mark Baker
+25  A: 

Don't detail the history of how code got to be how it is. That's what version control is for.

For example, don't do this:

// This method was originally called GetSalesDollars(), but now that we
// support other currencies, we've changed the name.  :)
Money GetSales() {
   // ...
}

or this

// oops.  This crashed if the denominator was zero
//return sum / n;
if (n != 0)
    return sum / n;
else
    return 0;

You might think such comments will be helpful to future readers, but honestly, nobody cares. This stuff is just cruft that will build up and make it harder to read the code. Tell your war stories in a bar or on your blog, not in production code.

Kristopher Johnson
The first one might be useful if there's some reason why people might be searching for "GetSalesDollars"
Mark Baker
Using Version control is overrated. What if this was changed a year ago. Are you going to dig back 20 commits in order to find that there was a change made?
James Dean
I think the 2nd example is a reasonable comment. In some places you do not have to test for division by zero, and in some you have because zero can happen there. The comment tells it is the 2nd case. The comment could be improved, but still it is usefull, so that no one removes the test later.
Suma
The concept of the second comment, if not this particular example, is good. If there is a known problem that needs describing so that the workaround is not removed when refactored then this should be commented.
BlackWasp
@James: you're going to run a _blame_ on the file and find out the last time that particular line of code was changed. Provided your team checks in discrete changes, it literally takes a few seconds to detemine why the line if (n > 0) was committed.
Dexter
Sometimes source control changes, sometimes old code from a previous project is copied back in after having spent 2 years residing in a branch off from the original mainline. There actually are NUMEROUS cases why relying on SOurce control is not good (liek the others listed above)
David Frenkel
@Mark, I'd argue that it would be better to create a GetSalesDollars method that passes through to GetSales with the appropriate options, and mark it as Deprecated.
Adam Jaskiewicz
why not? if some subtle things are not made explicit maybe some other programmer will assume they aren't and make the same errors...
fortran
It saddens me that we live in a world where some programmers think that checking whether a divisor is zero before using it is something "subtle" that needs to be commented.
Kristopher Johnson
Historical information can be useful - if the 2nd example above said "Fix for bug 001020 - n could be 0 due to user input"
David_001
@Kristopher: Sometimes numbers aren't going to be zero, for whatever reason (frequently because things don't make sense if there's zero of something, so it's tested earlier). Documenting that zero does show up can be useful.
David Thornley
Actually, thinking about it, the second comment is a sign of bad maintenance. If you need a quotient, and the denominator is zero, there's very likely a problem, and just returning 0 at the answer will give quiet wrong answers. The comment should explain why returning 0 is the right thing to do.
David Thornley
@David, I agree that comments indicating why 0 is the right value to return might be useful. But nobody cares about how it worked before the change to return 0, which is the point of this answer.
Kristopher Johnson
+2  A: 

IMHO, if you have a block of code that is complicated enough to warrant a comment, an alternative to said comment is to throw that code into a function that has a descriptive name.

Bill
+12  A: 

To me, comments are meant to explain why you did it that way not what you did. If you have to explain what you did then the code probably sucks and needs to be redone.

Flory
I disagree, your answer suggests that there should never been comments. Possible, what code is obvious to you may not be obvious to others.
Pool
+17  A: 

A great place to not comment code is when the code is self-commenting (i.e. variables are well named, program flow is clear, encapsulation has been used correctly, etc.).

However, as a caveat I would submit that knowing this about code you're currently working on is really hard for most people to do. This is because code that is currently being developed by you or those on your team is usually pretty obvious to yourself and your teammates. The time when comments really pay off is when a new developer either comes on to the team or has to begin to maintain a source tree that they have never worked on before. For instance, I recently began to look through the Wordpress source tree, and the fact that there are lots of segments of code that are uncommented or commented on by someone who clearly was very familiar with what the code did already has made it very difficult for me to get a grasp on the system right up front.

So, a 'best practice' might be the following (I don't actually do this, but I'm trying to get in the habit): When you write a new piece of functionality, get a fellow programmer in your team to come over, sit them down, and explain what your code does (or possibly better yet, try to have them explain what your code does) and, if that goes over without a hitch, you probably don't need a comment. If it is challenging, comment away, and long after you're no longer working on the project, that code should be clear to whoever has to work on it.

Another great benefit to this would be the following: Should you be unable to think of anything but an obfuscated way to implement a feature, if you clearly document your intention, someone who comes along later who might have a different flash of insight than you will be able to see what it's doing right off the bat and refactor it, knowing that they are still following the original intention of the code block.

That's my two cents at least.

Tim Visher
I would have to somewhat disagree with a small part of what you said. I htink if its complicated that it needs explanation, it should be refactored to be simpler and clearer first. If that is not possible, for performance reasons, or whatever, then by all means, go and comment the intention.
mattlant
Comments? We don't need no stinkin' comments! ;-)
Mike Spross
Yeah, I totally agree with you in an ivory tower type situation where you have an infinite supply of time and intelligence. The reason to use comments for this purpose is when you lack the intelligence or the time in the moment to refactor. Refactoring should then be done during a later iteration.
Tim Visher
@mattlant: That assumes that all code can be self-documenting if refactored properly, and I don't think that's true. Code that implements a complicated algorithm is likely to need documentation, at least a reference to the algorithm, to give one example.
David Thornley
A: 

Leave older versions of the code as comment is also quite a bad practice, too often seen.

Johan Buret
I think this happens (at least sometimes) because someone is testing code and they get it working and they're not diligent enough to double check the code before they check it into source control. At least that's been my experience.
Onorio Catenacci
+2  A: 

I think that you MUST comment any block of code that has business logic or code that seems to be doing something that follows rules that are relevant to the flow of your system so it wouldn't make sense to add a comment to tell the developer that you are looping through a collection but maybe it makes sense to tell the developer WHY you have to loop through the collection or why you break if X happens.

Gustavo Rubio
A: 

Commenting that is overly verbose is generally not only unnecessary, its a bad idea. Your comments, if needed, should be just as clean as your code if not cleaner. I only truly expect large blocks of commenting when the functionality is commonly used and thus elicits many questions or the functionality isn't clear.

Also, if you're in Visual Studio, I highly recommend GhostDoc as it can eliminate a lot of typing on your part for simple things that need documentation.

Russell Myers
+1  A: 

You should not comment when self explanatory code is enough.

For instance:

// Verifies if the "credit" ( or whatever ) is approved.
if( tries < 15 && x > 0 && x <= 1 && y != x || count == d  ){
    ...
}

Sure it deserves a comment. But this is way much better

if( isCreditApproved() ) {
    ...
}

Remember:

Blockquote

Any fool can write code that a computer can understand. Good programmers write code that humans can understand. -Martin Fowler

Blockquote

And everyone knows that comments are not executed.

OscarRyz
BlackWasp
Actualkly it doesnt need commenting.... It should be refactore3d AGAIN and given clearer variable names. Naming goes a LONG way to avoid commenting
mattlant
Yeah, if the variable names are made more clear (creditScore, totalBalanceOnRevolvingLOCs, stuff like that), and the magic numbers are replaced with named constants, it should be pretty clear what the code is doing to determine if credit is approved or not.
Adam Jaskiewicz
+56  A: 

Don't leave commented-out code in source files.

If you don't need it, then you don't need it. Delete it. You can always get it again from your version-control system.

If you think you might need it, then instead of commenting it, enclose it in a conditional-compilation block, move it to a separate function, or otherwise get it out of the way and clearly mark it as not-real-code.

Kristopher Johnson
Ditto. One of my pet hates
Mitch Wheat
I sometimes do this, but it's amazing how quickly that commented out code degenerates into something that works almost, but not completely, unlike anything else in the same class.
Paul Tomblin
Only time I think you should do this is when your live deployment is totally disconnected from your version control system. Being able to see latest edits is sometimes very handy.Otherwise I totally agree! That's why God gave us :CVSVimDiff in vim! (-:
Rob Wells
+1 to Paul's comment for HHGTG reference ;)
therefromhere
Sometimes I'll leave a block of code in there to remind myself that I've already tried to fix it - it didn't work and not to add the code again. I'll also include a reference to any relevant issue tracking record or support ticket to refresh my memory.
Paul Alexander
+8  A: 

I use comments for three things:

  1. Auto-Documentation: For use by IntelliSense systems, even if its 'obvious' by looking at the code. It infuriates me no end to see other libraries or apps that lack member documentation when I'm trying to browse them from IntelliSense, so I make sure to fill in all of mine.
  2. Justification: The best use of a comment, saying why the code exists or is needed. This shouldn't consist of too much 'how' or 'what' though.
  3. Summary: In larger methods or property lists, I title subsections or groups with a small comment to say what the section does for easier reading and parsing. As a side effect, if I find myself describing two methods with the same sub-section names, it helps suggest a possible location of duplication that I should refactor.
Nidonocu
I have seen documentation comment in private methods also. Style cop enforces them. Is there any reason?
Tanmoy
If you end up sharing the source of the library with other programmers so they can edit the library, it can certainly be a big help to have everything well documented and named.
Nidonocu
+2  A: 

Code should always be as absolutely self-documenting as possible. If you look at a piece of code and realize you can restructure it so a comment is no longer necessary, that is the best course of action, since it makes the code easier to understand.

Obviously, this doesn't mean you should never used comments--it means that code should be designed so as to be as understandable as possible before people look at the comments. Comments should be reserved for FIXMEs, explanations for non-obvious tricks/hacks/similar, and explanation of complex algorithms and functions. The majority of code should not need significant commenting.

Dark Shikari
+1  A: 

If a comment makes you feel stupid while reading it, you should really try to avoid committing that comment to your source control.

Example:

// I've no idea why, but this fixes Bug#0815:
i++;


If a comment makes you feel smart while reading it, you should really try to avoid committing that comment to your source control.

Example:

// This is the fastest strReplace *evarrr*!
// I got it from this nifty coding site:
// http://thedailywtf.com/Articles/My-str_replace()-Can-Beat-Up-Your-str_replace().aspx
function fixString($string, $chars = 0) {
    // ...


I have to admit that in both cases, the primary problem is not the comment. But they're a "smoking gun", so to say.

David Schmitt
+3  A: 

Almost all comments can be avoided using the Extract Method refactoring and giving a good name to the method.

I only comment code that can me misunderstood and removed by other programmer on the team, as an example, last week I had to comment a code when I used something like:

Field.Value <> Null

It would take, hum, let me think, 2 minutes until someone would change that to Field.IsNull, but the problem is that IsNull in a Aggregate Field, Always return True (if I'm not mistaken) in Delphi, so changing it to IsNull would introduce a bug.

But I extremely recommend you to think twice before writing any comments, comments are most likely needed when the code is bad.

Fabio Gomes
+5  A: 

I just love these:

//
// Set the DIB bits to the device.
//

result = SetDIBitsToDevice( ..10 arguments or so );
sharkin
Subtle and awesome.
Robert S.
+1 but guilty of these ...
Pool
+2  A: 

At worst, comments can lie. At best, they can be redundant.

They're usually only okay for something unintuitive. As in.

// HACK: If I don't call this twice, Foo breaks. 
Bar.Setup();  
Bar.Setup();

If you have a method like this

User.Save();
// Send confirmation email...

That's a code smell, and you should refactor to method.

User.Save();
sendConfirmationEmail();
ignu
+6  A: 

Based on a true story. Don't ask a question in comments for some other hypothetical person to answer:

// Crap, why is this here?
// Well, just in case it happens somehow.
if (i < 0.0)
{
  printf("Uh oh!\n");
  i = 175;
}

It's better just explain why something is there in the first place, and if you're doubtful, make sure you resolve the problem yourself, find the answer, or ask someone (your colleagues, stackoverflow, etc.)

Edmundito
Yeah, some people think comments are for their "commentary" on the code. I hate that.
Kristopher Johnson
My comment was based on a true story. :)
Edmundito
A: 

Saw this once in a class where we were told to "comment everything."

//This is pretty obvious
int num = 2;
//duh
char yesno = 'n';
//just declaring some more
char yesno2 = 'n';

...etc.

ray
A: 

If you reasonably can figure it out from the code, don't comment it. If the code's so complicated you can't understand it, change the code if you possibly can, rather than clarify with comments. Don't use comments to give a quick description of what a variable or class or function is for: use the name for that.

Typically, around here, comments are used to explain decisions (why is base_rpm 1200?), explain nonobvious things in the code (avoids the problem in case 1234), describes usage, or to give a high level view (calculates frammistan clearance using Howard's method).

David Thornley
+57  A: 

Don't comment the end of blocks. i.e.

if (...)
{
    ...
} // if

If your blocks are that big that you can't figure out where they start & stop, you seriously need to refactor your code.

Ferruccio
This rule should not apply to pre-processor statements I think#ifndef HEADER_NAME_H::#endif /* HEADER_NAME_H */Is a useful construct as these can be quite long blocks
Vagnerr
I've generally seen this from people who move from languages where control ends with a keyword (IF ... END IF, WHILE...WEND, etc). They say you always write code in the language you first learned ;)
tloach
Or even get a better editor that highlights the parens...
LiraNuna
@tloach - i definitely do that when i code in vb usually at the `else` statement to say why the else statement is necessary
Jason
I do this if the matching brace doesn't fit on the same vertical screen, or if there are a bunch of close braces all in a row. Sometimes it's just not possible or reasonable to refactor the code in such a way that you only have 20-line functions. That being said, I do agree that these comments are not a substitute for proper code factoring and organization.
Jon Seigel
+4  A: 

Important is what you comment. Do you comment what the code is doing, or do you comment your intention why you code it this way?

For me are comments that describes what the code is doing pretty useless. I can read the code by my self, but i can't read the mind of the other progammer.

knight_killer
+30  A: 

Whenever human possible, write code that doesn't need comments:

When you feel the need to write a comment, first try to refactor the code so that any comment becomes superflouus.

-Martin Fowler ("Refactoring: Improving the Design of Existing Code")

I think commenting code is a bad habit. Commenting code should remain something rare and exceptional.

The time is better spent with:

  • document your code (public methods, purpose of classes, runtime behaviour, configuration)
  • document your design decisions
  • let others review your code
  • automatic testing
Andre Bossard
Best response yet!
awhite
Rather than "don't comment your code", I'd phrase it as "Write code that doesn't need comments."
Kristopher Johnson
+5  A: 

Don't use comments in lines like

//if red is true then
if(isRed())
Agusti-N
+1  A: 

I just hate comments created by GhostDoc. As if

/// <param name="participant">The participant.</param>

Wasn't already obvious. And cleaning / enhancing that just to create a nice, documented framework is really tiring.

Currently I prefer using #regions rather than comments because they kind of wrap code so that you know without looking at identation when it has ended.

rshimoda
A: 

sorry rshimoda, I repectfully disagree. I use GhostDoc to ensure my methods/properties etc are correctly named. If GD does not automaticaly give me a comprehensive and clear comment then I need to rethink my method name. I agree the parameters are somtimes a bit obvious but its better than writing the whole thing yourself. After using GD my method names have become much more user friendly. this may be more of an idication of my coding than GD however.

RhysC
+2  A: 

A summary of my "favourites" (some mentioned above) would be:

1) Comment the intent of the code, don't restate what the code is already stating

2) Don't leave commented out code lying around - delete it. (That's what source control is for)

3) Don't have massive blocks of comments at the top of a class/module stating the history of changes to the code - they never maintained and therefore are completely out of date within one or two edits aside from being completely useless. (Again...source control)

Stuart Helwig
+3  A: 

I forget why I read it, so I'm probably going to misquote here, but:

Code tells you how, comments tell you why

Martin
A: 

I don't comment when code is intuitive/informative enough to show what is going on.

Zee JollyRoger
+1  A: 

When coding a submission to the IOCCC.

Windows programmer
+1  A: 

When not to comment code? Always! Let your code be self-documented!

Ngu Soon Hui
+1  A: 

The basic method to decide, to comment or not to comment the code is to look at the section (of the code), as if you were reader, and listen to yourself. If your internal voice want's to ask: "what the hell is this?!" - then you obviously need to place an explanation on the thing, that confused you so much, otherwise it's all depends on - what do you think, the reader (which is not you) will be able to get it right, or not. Also, I would quote someone of answerers with a little addition:

Code tells you how, comments tell you what and why

Alexey Shatygin
A: 

Many IDEs generate useless comments (especially Javadoc style comments). As an example here's what you get with a lot of them when generating getters and setters automatically:

int foo;

/**
 * Returns the value of foo
 */
int getFoo(){
  return foo;
}

/**
 * Sets the value of foo
 */
void setFoo(int foo) {
  this.foo = foo;
}
John Meagher
+2  A: 

If you have to explain it during a peer code review, it probably deserves a comment.

bk1e
A: 

I'd say don't comment code that is highly complex. The comment will leave future developers more confused about the behavior of the code. It is infinitely better to write unit test cases for such complex methods. Properly documented Unit Tests are much better than code comments.

Ashish C
+1  A: 

I once took over code with a lot of comments similar to the following in it:

function XYZ()  
{
... Lots of really bad code ...


/** f### the <some Client Name> again changed his mind, 
it is the third time this week I had to change this code, 
I am really getting <some more swearing > with this, what is it with him.  
Now I had to change this back to how I originally had it, , <some date> . **/

/**
Some code.
**/
... Some more really bad code all in one majorly long function ...  
}
Schalk Versteeg
A: 

In addition to the already-mentioned pointlessly trivial comments, there's an unpleasant habit here of putting ASCII 'borders' around them, wasting two additional lines.

//===========================================
// Log off from the system.
//===========================================
system.LogOff();

There is also a tendancy to use giant comment 'banners' to split code up into categories, like so:

//===========================================
//===========================================
//
// PRIVATE FUNCTION DECLARATIONS
//
//===========================================
//===========================================
int some_function();

Quite often I find myself playing a tedious game of 'spot the code.' One time I came across a perl file with 200 commented lines and 10 lines of code! This kind of thing really put me off comments, and I barely ever write any of my own now, preferring well-named short methods instead. (I've also set the comment highlight colour to the lightest shade of grey that I can just about read, which keeps the noise down quite well.)

So I guess my recommendation is if you really must comment, don't 'decorate' them and waste even more valuable screen estate!

marijne
A: 

I saw this the other day:

If x = y Then DoSomething   ' one line if

Thanks for the clarification!

pezi_pink_squirrel
A: 

Straight from Suns official Swing documentation (on tree widget nodes):

/**
 * Returns true if the receiver allows children.
 */
boolean getAllowsChildren();

Allows children to.. what exactly? Can I add nodes by drag&drop? Should the ui display a handle to open this node? May I still add children later when I said no?

Any half decent perl script could have made a better comment.

A: 

Comments can lie. Unit tests cannot. Use good variable/method names and write unit tests: then I'm happy.

Michael Easter
A: 

Perhaps part of the reason people find themselves adding comments is that they are being taught to do so. Teachers frequently require comments almost everywhere. It would be nice if teachers instead taught about intelligent naming of functions and the like, but this is insufficient because the normal strategy of knowing what a function does because it is well-written does not apply if code is poorly written.

It would make for an interesting assignment to give a student very well-written, working code and ask them to get rid of every comment yet make the code just as readable. However, classes tend to focus on theory rather than practice far too often, and it is more work to grade such assignments.

Brian
+1  A: 

When the comment can be removed by correct programming:

Bad code/comment:

// Remember to put a slash at the end
directory = "/usr/rush/data/";

Good code:

if (directory.last() != '/') {
    directory += '/';
}
+1  A: 
  1. Don't comment the obvious
  2. If you didn't comment and it wasn't so obvious after all, add a comment

If some code doesn't seem to make sense, you "fixed" it and it broke, chances are that the next guy will run into the same trap -> Needs comment.

So my rule is not to comment anything except to show people around ("this stuff works with that stuff over there to achieve whatever"). Basically the stuff that you simply can't put into code because your language simply doesn't support it.

Then I refactor code to introduce sense (like grouping repeated operations in a method with a telling name).

And when I find code that behaves unexpectedly and I can't fix it, I put a comment in there for the guy who has to fix it (who might be me). In an ideal world, I should be able to fix anything but the day has only so many hours, so something has to give and in this case, it's better to add a note instead of just walking away.

Aaron Digulla
A: 

The best programmer I ever met had a script that stripped out all comments. He always ran it before looking at the code. I was amazed.

"The comments never help," he said, "all they can do is convince you that bad code is right."

Nosredna
This memory prompted a blog entry about this theory... http://alifeprogramming.wordpress.com/2009/02/07/comments-are-always-wrong/
Nosredna
On my first real job, I was told to ignore the comments, since they'd only confuse me. This was a large program in IBM 370 assembler.
David Thornley
A: 

As many people here have posted, and I totally agree with, you should strive for comment-less code. You're native written language of choice doesn't compile and unit tests don't test it, so it's never going to be as up to date as regular code.

What comments should express is meta-information. I think of it this way. The code itself describes what it's doing. Good structure and variable/method names should provide most of the why the code is doing that. But what it can't express is the next level up; why the code is written that way and not another (for example). A lot of that history should live in the version control history of course, but some of it deserves to elevated to a more obvious in-your face placement. For me, that's what comments are for.

Examples include references for algorithms used.

// This tree traversal is from "Algorithm T", section 2.3.1 of Knuth vol 1. ...

// The rules to determine account eligibility were taken from the brainstorming session with // accounting on 3/23/09 ...

// This is using sort algorithm X on purpose; performance tests on real world data showed // it to be faster than the theoretically faster algorithm Y ...

The third one in particular is the majority of comments I try to make. Whenever there's an obvious way, but it didn't work for some reason, it's good to document that the obvious way wasn't ideal. Otherwise someone might come along and "clean it up" to be more obvious and run into the same issues that you ran into long ago.

Rob
+1  A: 

When you see the comment and think "No shit...".

I've seen code commented like this before.

if(isset($loggedIn)) { //if $loggedIn is set...
    if(!isset($_SESSION["commented"])) { //if $_SESSION["commented"] is set..
     //tell the user they're logged in but haven't commented
     echo "You are logged in but haven't commented this session"; 
    }
    else { //or...
     //tell them they have commented!!!!
     echo "YOU DID COMMENT!!!";
    }
}
    else { //or...
     echo loggedOut(); //output the function "loggedOut();
    }
Andrew
A: 

// rajan: 9985508700;rajat: 917716100

Vivek