92 comments

[ 4.3 ms ] story [ 154 ms ] thread
Or better use (and develop) a good judgement on where it's better to add some comment here and there if required. It doesn't need to be black or white. There are lots of gray in between.
Don't listen to this guy. Comment your code, because if its in production, your most likely not be the only hands that touch it!

Someone down the line will have to review it, change it or modify it. It saves both time and effort, if you comment the code.

Just do it.

Write code that other people can review, change or modify. If you're coding right, comments should rarely be necessary for that (and indeed would often just be a distraction).
> Just do it.

Seconded. I've got an algorithm here, and the comments are very helpful. In one place, an array is iterated over backwards which is important and would trigger a few edge cases if it wasn't the case. A quick comment to explain why it's being done makes it easier to read and less likely someone will change it without understanding the consequences.

Or, you know tests. Having a "defensive" comment (explaining some critical corner case) is just terrible, write a test that exposes it so code can be refactored. "WARNING" comments are a really bad thing.
Or, you know, both. Why not leave a comment explaining why a non-obvious code block was written. It's not an either-or situation.

I've left a before because of a subtle GC bug triggered only on particular hardware, which could not be replicated in the development environment, and would only be revealed by a particular coincidence in timings. How do you test that?

Or they will simply change or modify the code and leave the comment? Now the comment doesn't help, it's actually detrimental.
Perhaps testable comments?
Why should we keep adding more complexity overhead to our languages and toolkits instead of finding people we can trust to do the job right?
Because there is no one we can trust to always do the job right, and so a large code base will accumulate cruft over time. Just how carefully do you search out any possible comment referencing code you change? It's not always going to be adjacent.
That's true, but at some point you cannot automate quality craftsmanship. Making comments part of the automated compile/test process in my opinion crosses the line and would be more detrimental than helpful.

In this specific case I would prefer to add code review and emphasize practices like adjacency of comments to code. Code should be reviewed on a regular basis as well. We all make mistakes, but I think a habit of putting at least two eyes on it and of coming back periodically to review past work is better.

I don't pretend to know it's a good idea, and there's undoubtedly poor ways to implement it, but I think it's worth exploring.

Adjacency of comments to code helps, but not everything can be adjacent to everything else, and when necessarily disparate code necessarily interacts it merits a comment that cannot be local to both.

Putting multiple eyes on the code is great, but 1) isn't prevented by what I propose, 2) isn't going to be perfect (and can perhaps be done more effectively with fewer things to have to check), and 3) sometimes isn't possible (if someone is working alone, for instance).

As John Carmack recently put it, on a large project "[e]verything that is syntactically legal that the compiler will accept will eventually wind up in your codebase."

I guess my hesitation is that I think it would probably be implemented poorly and then be forced on me by a PHB. You are right in the points you make and if it could be done so that it did not add lots of mental overhead or required boilerplate it could be a useful tool. Worth exploring, but I'll let you do the exploring. :)
Testable documentation - or, as it's more commonly known, unit testing - is of course a very good idea, and a better replacement for comments.
Related, for sure. I think for it to be considered testable comments it would have to 1) be inline, 2) be brief enough to be easily readable in the context of a comment, and 3) be aimed at documenting the kinds of things good comments are aimed at documenting. All of these are occasionally aspects of unit tests, but there are plenty of things that are unit tests and are probably a good idea that are not all three of these.
That's not an indicator of comments being the problem, that's an indicator of someone that can't be bothered to update documentation.
Feel free to believe that comments are a good idea in some mythical perfect world of perfect programmers. They're still frequently worse than useless in the real world.
Feel free to believe that no comments at all are a good idea in some mythical perfect world of perfect programmers. Their absence is still frequently worse than useless in the real world.

I suppose in the end it's just a matter of opinion, isn't it?

That's a process/standards issue, not a problem with comments!

If a team is so poor that they don't properly document what they do I suspect that the comments is the last thing to worry about :)

> That's a process/standards issue

Same with shit code and non-self-documenting code no?

But some people won't read the comments. Or the article.
Yeah, but I think his example of good code was pretty confusing. I still think it's a good idea to section off your code into smaller modules - each module should complete one 'step' of the process (whatever that means for your particular program) - and each module should have a short comment at the begging of the section explaining what it's inputs/outputs are or generally why it's there. Some comments for exceptionally tricky stuff isn't a bad idea, but like other people said they are often ignored and might get out of sync with the code that's actually there.

But I still think some comments are better than absolutely no comments...

Sorry for the confusing code. I took a look back at it after reading some of the comments here, and I found that I or Blogger had mangled the post. Almost half of it was missing right out of the middle. It's updated now, so hopefully it makes more sense.
And this is how we end up with comments that documents what the code used to do ten revisions ago.
You must be doing comments wrong. If they explain the why, they should still be relevant. Or people should rewrite them when they adjust the code...
If they explain the why, they may be justified, but they will still eventually become invalid when the code is changed to do something with a different rationale.

And yes, people should rewrite them when they adjust the code, but like so many other things: In any reasonably large code base it sooner or later gets neglected because the code still runs and passes all tests without it.

If you want "documentation" that will stay up to date, you either need an extremely rigorous development process, which pretty much nobody has, or your documentation needs to be in the form of test cases that will break when the documentation is no longer valid.

I 30+ years of writing code, I've don't think I've ever come across a project of any reasonable size that haven't had substantial comments that were outdated. I would love to see such a beast - it'd be a little bit like encountering a unicorn.

If one cannot be bothered to update corresponding comments when updating code then I suppose they'll have problems updating the separated documentation as well.
no code will say WHY you did something the way you did it. only comments can do that.
That's right, and I think that was the point of the author:

> I may put a few words in a comment to explain why the code is doing what it's doing. If I find comments answering 'what' or 'how', I take that as an indicator that the code is not written well enough.

Sometimes you don't want to write the code "well enough" either, e.g. if you're reifying a standard algorithm I think it's a better idea to directly transcribe the original paper if possible, and stick as close to it as possible (including the usually dreadful naming conventions).

And in that case I usually add the paper's pseudocode above the corresponding transcription as well to make the mapping even clearer.

On the contrary, an approximation of some code I've written:

    function do_search($query) {
        if($database->type == "mysql") {
            return __do_search_stupidly_because_mysql_is_shit($query);
        }
        else {
            return __do_search_sensibly($query);
        }
    }
So a comment could explain why MySQL is shit, what versions, whether it applies to MariaDB, whether there's an open defect, how your algorithm is different, etc. Presumably whoever wrote this code learned some of that metadata, so it's helpful to keep a record of it.
Most usefully, I'd like to know what the consequences of doing the obvious thing are. Maybe they don't matter any more (high memory usage, cpu use, etc) and we can trim the codebase, or it's still a NEVER CHANGE THIS OR WE LOSE OUR JOBS level issue.

I'd much rather see a comment like

    /* 
     * Inputs of integers near INT_MAX cause significant CPU load
     * in MYSQL versions 4.2 <= x < 5.8 (latest at time of writing)
     * Bug tracker http://mysqlbugtracker/issue/4
     */
Than

    lolz_mysql_is_shit(foobar)
As a relevant point, we've got a large comment in our codebase linking to issues and discussions of the problem of excel reading csv files containing £ symbols with particular encodings. If you didn't know the issue, having `format_excel_is_dumb(file)` wouldn't help.

I am happy classifying comments as "you should have a reason to add it and keep it" rather than "bad code, always remove".

Still, I suppose it's hard to generate buzz with an article that says "use your common sense" rather than repeating an old absolutist viewpoint.

honestly I don't like this approach.

In my mind code is for the "how" to do a thing, comments is for the "why".

While sometimes some bugs in some library / infrastructure element bites you badly, I still think calling a function "do_workaround_XXX_because_YYY_is_shit" it's not a good practice. And, hey, in comments you can articulate your hate for mysql with more space :D

Why is it shit? What do you mean by 'stupidly'? Is this something that you intend to fix later when updating the mysql version, or is it something that will always be stupid? What are the performance impacts? Why not search both databases using the stupid method to avoid two codepaths which might diverge?

I prefer to be parsimonious with comments, but strange hacks, workarounds for bugs, and other places where otherwise clean code meets the real world should probably have at least some description of why that particular workaround was chosen, and not some other more obvious option.

"My code is so good it doesn't need comments!" says the first.

"What the hell was this guy thinking?!" says the second.

I wholly agree that code comments can be greatly reduced by better code, most notably with code that has well-named variables and methods as well as through reduced complexity through refactoring.

However, I think the way the OP title is phrased, "Don't Comment" makes too strong of a statement against comments, when I think the better, albeit softer statement would be: "Write Better Code and Fewer Comments"

The main argument against commenting period is that comments are inherently not part of the workflow/compilation process, so it takes an extra level of cognitive awareness and maintenance to make sure they stay up to date with the specs. Other than that (very big) hitch, there's nothing inherently wrong with comments...except that in practice, a huge number of them indicate a code smell, as well as being a maintenance liability.

This may have been outside of the OP's scope, but I think it's worth mentioning that well-written and copious tests can also serve the function of comments...unlike comments, they do break when the code they document is changed, and so thus they're easier to maintain in that you can't go forward without fixing them (which introduces its own maintenance chore, and so on and so on).

Yes, I was thinking the same thing. Your title suggestion is more accurate, but would probably draw less clicks.

I prefer it when a title is bland, but the content is so astoundingly good. These are little surprises and they still find their way to the front page.

I used to argue that well-written code needed no documentation, but I read various articles about documentation anyway.

The takeaway was this: Even if my code is clear, neither I nor anyone else should have to read through a function in order to understand what it does. Reading a comment should be enough to use it.

This has the additional advantage of separating the specification from the implementation. If e.g. a javadoc comment says "@throws IllegalStateException when foo", then I know if I change the method, I have to preserve that behaviour.
I'm a proponent of self documenting code (method names, variable names, immutable variables etc) but this only helps document the WHAT and sometimes HOW but seldom the most useful WHY or WHY NOT or what I have tried before this and what didn't work so I changed it.
I find it good practice to comment code for that other guy that is me-in-two-months. I just rediscovered some semi-old code and boy am I happy about the comments.
Yeah, good comments help support DRY. Not so much DRY in the code, but avoiding repeating the mental work that led to the code (whether yours or somebody else's.) If the code is non-trivial, there is probably research, discussion, or analysis that went into producing it that the next person working with the code (whether you-in-N-months or someone else) either won't have done or won't have as fresh in their mind when they look at the code. Summarizing or providing references for that work stops it from being redone (or, worse for the code, the lessons forgotten and the mistake that it avoided reimplemented.)
"Don't comment bad code -- rewrite it." -- The Elements Of Programming Style by Brian Kernighan and P.J. Plauger. 1974.

Until your code is as good as Kernighan's you probably want to comment what you intended to do.

Kernighan does not say "don't comment good code"
You can read what Kernighan wrote here: http://books.cat-v.org/computer-science/elements-of-programm...

Also see Software Tools and The Practice Of Programming.

He really doesn't say "don't comment good code".

Reading page 141, he generally recommends that everyone should comment their code for non-trivial programs. Also, "One thing we will _not_ do is make pronouncements about how many comments a program should have."

KISS!!

comments describe why. code describes what.

I thought this was just another stupid HN comment. Had to read it several times for it to make sense. Its solid advice.
Speaking from experience of a) working in a team and b) maintaining legacy code: Your code, no matter how good, will not instantly make sense to someone else.

Comments are essential. Writing good comments is as skilled a task as writing the code.

(as an aside; the most important comment is WHO. Because knowing who wrote/modified a block of code is ridiculously useful for all sorts of obvious reasons)

svn / hg / git ... blame ? :D
Even CVS has an annotate / blame / praise command as well, as do, for example, commercial systems like Clearcase and MKS source integrity.
If you have to write who wrote a piece of code in a comment, you must not be using a decent version control system with a blame command. Which is a problem you should probably fix way before talking about comment styles.
Uh, that takes much longer.

Blame is useful in more elaborate context but... comments are instant :) And that is important.

> Blame is useful in more elaborate context but... comments are instant

Blame is instant too, if you have a good and modern IDE. Can't always be relied upon, but once such a beast exists, just assume it's being used. Writing erlang? Sorry, inline comments. Writing JS/PHP? Leave it in git.

Fair point, but I have two counterpoints:

1) Changing version control systems may be an unwinnable corporate political battle, while changing comment style may just be a team decision.

2) Not everyone who may need to understand or modify your code may have access to your repositories. I worked on a program where partner companies were provided source snapshots for developing their own algorithms but were not allowed access to our repositories.

> Because knowing who wrote/modified a block of code is ridiculously useful for all sorts of obvious reasons

IME, the only use it usually has on its own is knowing which people that are no longer on the team to blame to blame for the poor state of the code (both the operational parts, and the absence of useful code comments on the intent or rationale for the current code structure.)

WHO is not the most important comment (though its probably the most universally necessary part of a comment -- a need for a who comment always implies the need for some other comment, and most other comments should include a who.)

I'm coming from a team whose policy is to create a PHP docblock for everything. This is actually dead useful because at a glance you see who wrote the code, exactly what you can pass into the function and what it will spit back out.
What are those "obvious" reasons?

The only reason I've ever had for knowing who wrote code is if the code+comments+tests do not adequately explain what's going on and I need to know. On most of those occasions the person who wrote the original code had already left the organisation.

I use comments where nescessary but what I really wish the IDE's/editors had was the ability to hide all comments (not just fold but completely hide), I don't need to see the comment now as I'm writing the code and the model is in my head but I will want to see them in 3 months.
Its true one should FAVOUR self documenting code. Going to the absolute and never commenting your code is obviously stupid, there will always be cases when more context and information on "Why" is needed.
"don't comment your code", as dogma, without thinking, it's just stupid.

What sometimes happens, when you work on the same code base for month and you know it inside out, it's that you get some knowledge for granted. So you shift your mental needs (and the need to comment it out) from the "how the hell do I do this" from "why the hell do I need to do this" (there can be some crazy business rules, or some infrastructure limitations or whatever).

The problem is, the knowledge of the code base is not easily transmissible from people to people. So it's still useful to leave some comment, specially on some "non intuitive" steps.

    The problem is, the knowledge of the code base is not easily transmissible
    from people to people. So it's still useful to leave some comment, 
    specially on some "non intuitive" steps.
Having just come from a team where code was well-written but poorly documented, this is important. It is the difference between it taking me 20 minutes and 4 hours to implement and test a small change. If the code is well-documented I can quickly find my way around and locate the behaviour I need to change. Again, if it is well documented it is easy to see how this relates to the rest of the system and I can make good decisions when I make my changes. If the whole process is well-documented I have a good starting point for what acceptance tests I should run to make sure it works as intended, and what kind of regression tests I should put in place or modify.

Without documentation I must read and decipher a much larger body of code, much of which ends up being unrelated to what I am working on now. Even in the best code-bases there will be code that is not clear without a pre-existing knowledge of the code-base as a whole. I am likely to make time-consuming mistakes because I do not understand some edge-conditions or complex interaction.

"My code is so good it doesn't need comments" is usually untrue. Don't fall for it.

If you can name an API or framework that you use that has near-zero comments... And benefits from that, I'd like to know. I can name plenty that are a pleasure to use because of clear, replete documentation.

If you're thinking your code is different from an API, you're right - it's worse. An API is designed for consumption, whereas your code is buried. It might not get look at by another human for months... or years.

Who will be looking at that piece of code next? You? Ok. Be your own worst enemy. More than likely it's someone else looking. And why? Maybe because it doesn't work like it should, or conditions have changed, or it needs to be extended.

Bad documentation can be just as bad as bad code, but "don't comment your code" is a road to madness.

"My comments are so good they don't need code" is usually untrue too...
No, it's untrue all the time because it doesn't make any sense.
Surely it depends on what your program is trying to not do.
My favourite piece of code that used to be in our code base was a set of empty PHP files with the comment "this file intentionally left blank". Created so that the core framework could be unit tested.

(This was before I came on board and introduced the idea of filesystem mocking).

See also Word press's "Silence is golden" php files.
> "My code is so good it doesn't need comments" is usually untrue.

I still don't see this as a convincing argument.

Our greatest constraint is time. So the question becomes do I spend my time writing comments or do I re-factor the code I wrote to make it more readable?

I always opt for re-factoring my code.

Have you read some of the comments most developers leave? They either explain the most obvious inane functionality or use it as their personal todo list. And sometimes they do both. That is not helpful.

In instances where I know my code will be a critical component which will be utilized by many others, I opt to write documentation rather than comments. And there is, of course, a difference.

Comments are inline, documentation is frequently split out. Comments are frequently inane explaining the obvious, while documentation goes in-depth into not only how the code works, but what it is trying to accomplish and why. Documentation also provides examples of use, which is far more useful than anything else. When I reach for the documentation option, I almost always include a separate markdown file with the same name as the original file. There are then a ton of options in terms of software that aggregate those files into a searchable, indexed collection.

Focus on code quality and if some sort of annotation is necessary, write documentation, but don't leave comments.

Inline documentation done right is undeniably a massive time-saver though because you don't need to search a separate document at all. With the right editor, your documentation can also be folded into a single line or be hidden altogether.

Can you show us any concrete examples of high quality, comment-less codebases? The last (mostly) comment-less source that I read through last year was Node.js and I wouldn't exactly call that high quality or well documented.

> Can you show us any concrete examples of high quality, comment-less codebases?

No.

Quite simply, there is a collective perception that if a codebase lacks inline comments, it's of poor quality. Very few would dare to publish such a work.

I have a different challenge for you.

Take a high quality codebase and delete all the inline comments. You'll find it's just as readable, if not more so. How much better would it have been if the coder had spent the time writing better code rather than adding superfluous comments?

"The coder" probably should spend time talking to customers, testing designs, interacting with their peers, reading other code, learning.

None of these contribute directly to achieving a theoretical maximum output of SLoC. If that's you're metric, I don't think it's a good one.

Aside from niche projects - A great deal of time goes into realising software. The incremental cost of comments is minuscule.

I have lots of challenges and bottlenecks. The time to type comments isn't one of them.

> a theoretical maximum output of SLoC. If that's you're metric, I don't think it's a good one.

That's certainly not my metric and I definitely don't believe it's a good one.

My metric is readability. The ability to return to a piece of code 6 months down the road and be able to understand precisely what's happening.

> I have lots of challenges and bottlenecks. The time to type comments isn't one of them.

Oh, I know. It's very easy to add a comment that you think will help clarify things down the road, but instead, ends up being more cryptic than your code.

By definition, a comment is something short and half-thought out. It's a comment.

As I said in the post up above, stay away from comments. If you have to annotate, write documentation instead.

That's not the definition of the word "comment" at all.

Who is the authority on whether commentless code is good or not? Could this possibly be completely subjective? Hmmm.

> Oh, I know. It's very easy to add a comment...but [it] ends up being more cryptic than your code.

You don't know that :)

Personally, I like Linus's take on comments:

"Comments are good, but there is also a danger of over-commenting. NEVER try to explain HOW your code works in a comment: it's much better to write the code so that the _working_ is obvious, and it's a waste of time to explain badly written code.

Generally, you want your comments to tell WHAT your code does, not HOW. Also, try to avoid putting comments inside a function body: if the function is so complex that you need to separately comment parts of it, you should probably go back to chapter 6 for a while. You can make small comments to note or warn about something particularly clever (or ugly), but try to avoid excess. Instead, put the comments at the head of the function, telling people what it does, and possibly WHY it does it."

https://www.kernel.org/doc/Documentation/CodingStyle (Chapter 8)

Hmm, maybe I'm just assuming Linus Torvalds wrote that - it could be another kernel dev.
I read the second block of code before the first. Just reading the second blob, I had no idea what the code was actually doing. Part of this is because I only have a peephole view into what's going on. I don't know what CalculateResultPairForNextStage() does, for example. My only clue that DMA is even involved in this code is the comment about resetting the source. Perhaps you have a big beautiful block comment in the header that explains what this component does, but just looking at this example things are far from clear.

I'm also wary of the refactoring. The _csHoldoff check and decrement happens every loop in the first block, but only once at the end in the second block. Of course I have no idea what _csHoldoff is or does, nor do I know why there's a "cs" prefix on it. Hungarian notation? Some variables have it, and others, like _centerFrequency, don't.

linkbait title. not a very good article. I think most of us here know about the dangers of stale comments, or spammy comments. I also think most of us know that writing good, descriptive, and up-to-date comments is basically essential.
"Clarity" is not a substitute for comments. The only thing I've seen that really substitutes for comments is a rich, easy to understand unit test suite. But even that is problematic, as it usually covers a lot of edge and corner case situations that aren't relevant to the end user.
I was trying to write good code instead of document a lot. But now I feel that a few comments is necessary, given that you write the stuff that matters. Maybe we should all try to comment as concise as possible, and write it just like SEO.
(comment deleted)
The problem with this is that he assumes the context will always be known to the reader.

I find that many assumptions about what is obvious in code have to do with the context the code is in. That context may be closely surrounding the code block, or with may extend to many lines before and after. If you have not been working on that entire section for a time, the context is not present (or only partially present), and as such all your thoughts on what is obvious may be subtly wrong.

This is analogous to program state. The farther you explore in either direction of the target code, the more of the possible state you can infer. Comments help is make these inferences without having to explore as much. Without comments we are forced to explore more of the program to build a better mental model of the possible states. Comments help us by providing hints as to the context (state).

Ah yes, there's nothing like wanting to use the new hot API and realizing you have to read almost all of the source code to understand how to use it because the code is so good it didn't require comments. Because I see good comments as a form of documentation. Can comments be abused and detrimental? Sure, but then so can code.

Especially in Javascript where parameters of a method are not typed, so if you want to know whether you should be passing a string or a number you have to read through the code to find out.

Or, you know, a single line comment saying what to pass might be helpful.

The problem is not the comments. The problem are the coders that follow behind to update a block of code but can't be bothered to update the comments to reflect the changes.

If your code is so good it doesn't need comments then it seems it wouldn't require git commit messages either.

Please don't summarize what your functions / methods do, make me read them in their entirety to find out.

Er, what?

"Illiterate Programming" paradigm?

I have been coding for over thirty years and the best reason for commenting your code is that the older you, will not remember what the younger you was thinking when he wrote the code.