

Don't Comment Your Code - Write Better Code - koblenski
http://sam-koblenski.blogspot.com/2013/07/dont-comment-your-code-write-better-code.html

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

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

~~~
WayneDB
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.

~~~
maratd
> 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?

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

~~~
maratd
> 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.

~~~
WayneDB
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 :)

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

~~~
lawn
Or they will simply change or modify the code and leave the comment? Now the
comment doesn't help, it's actually detrimental.

~~~
dllthomas
Perhaps testable comments?

~~~
lmm
Testable documentation - or, as it's more commonly known, unit testing - is of
course a very good idea, and a better replacement for comments.

~~~
dllthomas
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.

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

~~~
spellboots
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.

~~~
ErrantX
Uh, that takes much longer.

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

------
amouat
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](https://www.kernel.org/doc/Documentation/CodingStyle)
(Chapter 8)

~~~
amouat
Hmm, maybe I'm just assuming Linus Torvalds wrote that - it could be another
kernel dev.

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

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

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

~~~
jdbernard

        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.

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

~~~
mhaymo
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.

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

------
nakedrobot2
no code will say WHY you did something the way you did it. only comments can
do that.

~~~
Shish2k
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);
            }
        }

~~~
foobarbazqux
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.

~~~
Shish2k
Those things are commented _within_ the function; but the name of it allows
the casual reader to know that madness lies within and they would be happier
for not looking at the innards at all :P

~~~
foobarbazqux
Ok, makes sense. By the way, switching on a type code like that is the classic
use case for virtual functions.

[http://sourcemaking.com/refactoring/replace-conditional-
with...](http://sourcemaking.com/refactoring/replace-conditional-with-
polymorphism)

------
russelluresti
Worst. Advice. Ever.

Please comment your code. First, you're probably not going to immediately
remember what the code does 6 - 12 months after you write it and when you have
to come back to it for an update it's going to take you too long to figure out
if you actually read the code. Comments make familiarizing yourself with your
old code much faster. Second, any other teammate who touches the code is going
to hate you if they have to read your code to figure out what it does. There
is nothing worse than looking over code written by someone else when there are
no comments.

~~~
dkuntz2
I disagree. And I'm not sure you caught the tiny part at the beginning when
the author talked about how _why_ comments are good, but _what_ and _how_
comments are mostly useless. Yes, there was only a tiny mention in the post,
but it was there.

I think that what and how comments are useless because they're literally the
code itself. Comments like 'increment by two' are useless, because the next
line literally says `x += 2`.

If that comment was expanded to be something like 'increment by two because
...', explaining why x is being incremented by two, it becomes useful, and I
think the author agrees.

I think the reason these posts get as much traction as they do every time
they're posted is because people tend to write bad comments. In my experience
as a CS tutor at my college, most new programmers either write useless
what/how comments or no comments at all.

The problem I see with these posts are that they don't talk about how there
are good kinds of comments, but that everyone should just make their code
cleaner and everything will be great. If more time was spent talking about how
to write better, more informative, and relevant comments I'd like these posts
more.

------
MetaCosm
Comment rot is like wiki rot -- all too common, and often more confusing.
There are a couple good rules of thumb I follow.

1) If you are writing a comment, make sure it is a "why" and not a "what" (why
this code exists, not a description of what it is doing). Why comments often
survive refactoring, you might entirely redo the login system, but the reason
you do it is still so people can log in.

2) If you find yourself documenting the "what" about code -- take a moment,
and think really hard about why it is confusing. If it is accidental
complexity (your fault), refactor it. If it is fundamental complexity (problem
domain is a bitch), don't add the documentation to the function, put that
knowledge in the tests. Nothing is as harmful that a bunch of gotchas buried
in comments no one will read, and will eventually rot and not even make sense
after the code is refactored.

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

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

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

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

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

~~~
_ZeD_
Kernighan does not say "don't comment _good_ code"

~~~
gregjor
You can read what Kernighan wrote here: [http://books.cat-v.org/computer-
science/elements-of-programm...](http://books.cat-v.org/computer-
science/elements-of-programming-style/elements_of_programming_style.pdf)

Also see Software Tools and The Practice Of Programming.

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

------
hyperbling
KISS!!

comments describe why. code describes what.

~~~
spoiledtechie
I thought this was just another stupid HN comment. Had to read it several
times for it to make sense. Its solid advice.

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

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

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

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

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

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

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

Er, what?

"Illiterate Programming" paradigm?

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

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

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

~~~
chevas
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.

------
dirkdk
+1 I like to refactor just names of variables and methods, instead of writing
comment what it actually does.

