share
Stack OverflowWhen NOT to comment code
[+47] [58] hstoerr
[2008-10-02 17:40:01]
[ documentation comments ]
[ http://stackoverflow.com/questions/163600/when-not-to-comment-code ] [DELETED]

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 [1] - such that it remains a collection of answers, not a convoluted discussion. Compare also Commenting code [2], Do you comment your code [3], and What's the least useful comment you've ever seen? [4]

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

[+84] [2008-10-02 17:43:40] Jim C

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.


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
1
[+67] [2008-10-02 17:45:08] Kristopher Johnson

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.


(14) 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
(5) What if you know that your colleague is an idiot who can't understand the code? - Marcin
(14) Littering the code with comments won't make the idiots any smarter. - Kristopher Johnson
2
[+64] [2008-10-02 20:16:57] Ferruccio

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.


(7) 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
(4) 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
(1) @tloach - i definitely do that when i code in vb usually at the else statement to say why the else statement is necessary - Jason
(1) 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
3
[+61] [2008-10-02 18:19:45] Kristopher Johnson

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.


Ditto. One of my pet hates - Mitch Wheat
(3) 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
(2) +1 to Paul's comment for HHGTG reference ;) - therefromhere
(3) 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
4
[+51] [2008-10-02 17:51:39] Rob Wells

Worse case I've seen is:

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

Serious horror!


Heh, that is terribly but also nice since it made me chuckle! - David The Man
(24) It's a horrible comment, but also a symptom of asinine management practices - Dana
I don't have any problem with it. :-) - Brian Knoblauch
(14) I prefer this comment rather than "// add one to i" - Turambar
(13) 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
[+39] [2008-10-02 20:38:58] Andre Bossard

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" [1])

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
[1] http://rads.stackoverflow.com/amzn/click/0201485672

Best response yet! - awhite
(5) Rather than "don't comment your code", I'd phrase it as "Write code that doesn't need comments." - Kristopher Johnson
6
[+28] [2008-10-02 17:44:45] JeeBee

// 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++


(7) Also adds one to your rating :) - Victor Hurdugaci
7
[+27] [2008-10-02 17:54:20] Kristopher Johnson

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.


(2) 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? - Jeroen Dirks
(4) 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
(2) 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
8
[+17] [2008-10-02 17:57:39] Tim Visher

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.


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
(1) 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
(2) @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
9
[+14] [2008-10-02 17:55:37] Flory

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.


(1) 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
10
[+9] [2008-10-02 17:49:04] Jesse Dearing

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;
}

(8) 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 to return 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
(2) 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 - GManNickG
You should put this into a comment though. Maybe like // Directly returning the result instead of first storing it in a local variable because we only use it once and this way it's shorter but doesn't detract from the readability. - Robert
11
[+9] [2008-10-02 17:53:18] mattlant

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.


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
12
[+9] [2008-10-02 18:21:02] Nidonocu

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.

(1) I have seen documentation comment in private methods also. Style cop enforces them. Is there any reason? - Tanmoy
(1) 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
13
[+6] [2008-10-02 17:44:40] Kevin Fairchild

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.


14
[+6] [2008-10-02 19:53:03] Edmundito

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.)


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
15
[+5] [2008-10-02 17:47:29] levi rosol

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.


16
[+5] [2008-10-02 17:52:52] Prakash

What’s the golden code/comment ratio? [1]

[1] http://stackoverflow.com/questions/111563/whats-the-golden-codecomment-ratio

17
[+5] [2008-10-02 19:32:18] sharkin

I just love these:

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

result = SetDIBitsToDevice( ..10 arguments or so );

Subtle and awesome. - Robert S.
(1) +1 but guilty of these ... - Pool
18
[+5] [2008-10-02 20:26:49] knight_killer

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.


19
[+5] [2008-10-02 20:42:08] Agusti-N

Don't use comments in lines like

//if red is true then
if(isRed())

20
[+4] [2008-10-03 00:17:42] Martin

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

Code tells you how, comments tell you why


21
[+3] [2008-10-02 17:49:48] Torlack

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.


22
[+3] [2008-10-02 19:08:48] Fabio Gomes

Almost all comments can be avoided using the Extract Method [1] 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.

[1] http://www.refactoring.com/catalog/extractMethod.html

23
[+3] [2008-10-03 00:01:44] Stuart Helwig

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)


24
[+2] [2008-10-02 17:43:46] KernelM

Don't comment every line, eg:

i++; // increment i by 1

j = "foo"; // set j to "foo";

ETA: Whoops, a bit late.


25
[+2] [2008-10-02 17:53:18] Patrick McElhaney
// 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.


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
(3) 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
26
[+2] [2008-10-02 17:54:34] Bill

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.


27
[+2] [2008-10-02 17:58:58] Gustavo Rubio

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.


28
[+2] [2008-10-02 18:22:52] Dark Shikari

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.


29
[+2] [2008-10-02 19:36:21] ignu

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();

30
[+2] [2008-10-03 02:58:40] bk1e

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


31
[+2] [2008-10-03 22:35:10] Brian

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.


32
[+1] [2008-10-02 17:43:26] mxg

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.


"When too many comments obfuscate the code" ... then it hightime to back off! - Andre Bossard
33
[+1] [2008-10-02 17:58:37] Johan Buret

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


(1) 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
34
[+1] [2008-10-02 18:08:42] Russell Myers

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 [1] as it can eliminate a lot of typing on your part for simple things that need documentation.

[1] http://www.roland-weigelt.de/ghostdoc/

35
[+1] [2008-10-02 18:11:23] OscarRyz

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:

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

And everyone knows that comments are not executed.


The problem here would be that the isCreditApproved method would probably be... return tries < 15 && x > 0 && x <= 1 && y != x || count == d. This in itself probably needs a comment, or at least some work to explain what this series of operations does. - 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
36
[+1] [2008-10-02 18:29:03] David Schmitt

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 [1]", so to say.

[1] http://www.urbandictionary.com/define.php?term=smoking+gun

37
[+1] [2008-10-02 20:00:38] ray

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.


38
[+1] [2008-10-02 20:10:25] David Thornley

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).


39
[+1] [2008-10-02 21:08:40] rshimoda

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.


40
[+1] [2008-10-02 23:50:38] RhysC

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.


41
[+1] [2008-10-03 00:22:53] Zee JollyRoger

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


42
[+1] [2008-10-03 00:44:55] Windows programmer

When coding a submission to the IOCCC.


43
[+1] [2008-10-03 00:49:01] Graviton

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

[1] http://itscommonsensestupid.blogspot.com/2008/03/one-single-tip-to-comment-your-code.html

44
[+1] [2008-10-03 02:19:16] Alexey Shatygin

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


45
[+1] [2008-10-03 02:41:11] John Meagher

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;
}

46
[+1] [2008-10-03 07:26:17] Schalk Versteeg

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 ...  
}

47
[+1] [2008-10-03 09:27:53] marijne

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!


48
[+1] [2008-10-03 09:36:58] pezi_pink_squirrel

I saw this the other day:

If x = y Then DoSomething   ' one line if

Thanks for the clarification!


49
[+1] [2008-10-03 11:16:05] Shadow

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.


50
[+1] [2008-10-03 15:29:57] Michael Easter

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


51
[+1] [2008-10-04 08:21:18] user20282

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 += '/';
}

52
[+1] [2008-11-11 16:30:14] Aaron Digulla
  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.


53
[+1] [2009-07-28 08:33:35] Rob

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.


54
[+1] [2009-11-20 00:40:06] Andrew

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();
    }

55
[0] [2008-10-03 07:24:11] Ashish C

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.


56
[0] [2009-01-31 23:20:59] Nosredna

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."


This memory prompted a blog entry about this theory... alifeprogramming.wordpress.com/2009/02/07/… - 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
57
[-1] [2008-10-02 17:44:33] hstoerr

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.


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
58