
Should I Comment My Code? The Case Against Code Comments - jordanhudgens
https://www.crondose.com/2016/10/should-i-comment-my-code/
======
celticninja
I'm a junior/trainee developer and I was advised that comments should explain
why something is happening, not what is happening. The what should be self
explanatory by reading the code, but knowing why something is being done is
useful when you, or someone else, has to look at it again in the future.

~~~
herbst
I learned to code in a way that the variable and function names also would
tell you the why. And otherwise the git log is your friend.

Tl:dr; i only do comments to excuse really stupid code.

~~~
hellofunk
No one wants to look through a lengthy git log to find the reason something
was done to a particular block of code!

~~~
herbst
I assume every damn editor out there has a plugin that makes this a complete
non issue. I spend most of my time in a terminal anyway and know my way around
it, i prefer it by far to comments, also because of the metadata like dates
and authors which rarely is found in comments.

~~~
michael_h
Half of the time, when I look at the git blame for a certain line, I get:
'whitespace-only change'

------
hellofunk
Not mentioned in this article is the effect that dynamic typing vs. static
typing has on how you comment. It is common practice in Clojure, for example,
to heavily document every function, because it is a dynamic language and there
are no other obvious ways to indicate the types of arguments or the function's
return value (though that is gradually changing in the language, but not
entirely). This practice is so encouraged and standard in Clojure that all
functions can be defined with language-standard documentation strings that
become a part of the function definition, which can then be looked up at the
REPL.

Some statically typed languages don't suffer from this particular problem of
making types clear, so you will see comments less, and reserved more for cases
where logic is hard to parse conceptually. But some static languages have a
similar problem due to type inference, which causes commenting in the same
fashion as a dynamic language.

I am of the school of thought that except for making types clear, the best way
to comment your code is to make the code as clear as possible so that it is
obvious without extra explanation. Often, you can refactor a clumsy or
confusing piece of code in a way to make its intent clear.

But sometimes you cannot, and that's where comments come in.

~~~
jordanhudgens
That's a great point, that can make a difference for when comments are
applicable.

------
SCdF
IMO there are two legitimate places for comments:

\- Public facing APIs where you're very specifically clear about how something
works, to be consumed by people who don't intend on or need to read your code

\- Explaining away seemingly weird code, odd choices, things new developers
might think are mistakes but aren't, choices that may not on the surface
appear to be important for performance, or solving edge cases etc.

~~~
NateDad
Everything is a public facing API. The private function you wrote is public to
the person who is fixing a bug / adding a feature to the code (which might
still be you, a year from now).

~~~
SCdF
Right, but the person fixing the bug or adding the feature is going to be
reading the codebase. I don't want to have to read a libraries codebase just
because I want to use it's public funcitons.

~~~
NateDad
Certainly. I just mean, documenting private code is almost as import as public
APIs.

------
newscracker
I find the argument not very strong. While stating that comments will become
outdated, the author also states that he uses comments for code organization.
There's nothing inherent about code organization comments that would somehow
make them less likely to become outdated or not used at all (header styles
wouldn't be prevented from going under some other comment heading by default,
to take the example the author stated).

I write comments for a few different reasons, the most important being to
document my thought process at the time of coding and to note other approaches
that failed or why it's done in a specific way. This helps the coding process
itself.

Focusing on the what and why makes it easy to skim through code that someone
else (including one's past self from several months ago) wrote. While good
naming could help to some extent, there is no substitute to longer comments to
capture thoughts and assumptions that could be revisited in the future to
learn from as well as identify opportunities for improvement.

------
blowski
The best place for documenting code, ranked from best to worst:

* the code itself - I.e. function names, class names, parameter names

* test and assertion names

* comments in code

* comments in tests

* version control repository commits

* some external documentation repo like Confluence or MediaWiki

Comments are good when they describe why, not how or what. For example, good
comments might be "Had to do it this way to support v2 of the API".

I hate going to documentation for an API and seeing "setFoo() - sets the foo
value".

~~~
asah
Big +1. One clever trick: put the URL of the design doc inside the code as a
comment.

------
nickcw
If you change code, then you should change any comments about that code.

Comments that don't match the code should be flagged in code review.

~~~
dmichulke
Related quote:

Code never lies, comments sometimes do. \- Ron Jeffries (says clojure-
emacs/cider)

~~~
asah
ROFL. I get the sentiment... but respectfully disagree: code lies all the
time.

To make a few... \- misleading function/variable names \- improperly captured
errors/exceptions \- improperly structured locking/concurrency \- code that's
overly complex or naively simplistic eg naively insecure.

~~~
dahart
This is a great point, code is often very messy, and often misleading the way
it's written, and often has bugs.

But, fwiw my reaction to your first line is that to announce your disagreement
is to not get the sentiment of the quote. What he meant was that code is
executed and comments are not. When he said "code never lies" he meant that if
your code is buggy, then the bugs will be experienced by users. So your point
is actually orthogonal to the point being made, and doesn't either refute or
support the quote.

------
martinaparicio
Once I had to work with a well written but undocumented NodeJS application (in
ES5, dynamically typed). I didn't know what to expect from any function,
neither the structure of the data. Suppose you have a function that returns an
Employee, but you do not know how the Employee is defined, so you need to look
on the database schema to know the basic structure -- but when you use it you
see that there is data that wasn't in the initial definition! The Employee is
mutable and some data was added in some place along the app. Good look finding
the actual expected output! This is easily fixed by adding some comments about
the expected data returned by the function.

Please, just document your code and update if any code comment if needed. It's
cheap and easy.

~~~
douche
Yikes. That's one of the things I like least about dynamic languages. Being
able to add properties onto an object after it is initially defined willynilly
is a disaster for trying to understand what is going on.

------
NateDad
Comment your code.

Top level comments explain the purpose behind a function or type. It can
explain nuances that can't be discovered from the name (does this function
append a newline at the end? Does it ignore empty values? What happens if this
value is null? etc).

Aside from trivially bad comments (i.e. "add 1 to n"), comments are almost
always helpful to get into the head of the person that wrote the code (even if
that person was you, a few weeks ago). Comments are great at explaining why.
Why this code exists at all, why it's doing things the way it is, why the hell
we're removing the last character of this string, etc.

Sure, you should write clear code... but there is no way that a function name
can convey all the details of the function... otherwise the name would be as
long as the comment you put above it:

IndentJsonWithTheGivenIndentStringAndReturnWithoutTrailingWhitespace

If your comments are getting out of step with the code - you need better code
reviewers. Code review should be a part of any professional development
organization. If you're just hacking on a side project on your own... then
yes, it means you have to review your own code. This is a skill, it takes
practice, but one of the things you should always be looking for is "do the
comments match the code?"

I would be very VERY skeptical of any experienced developer that said they
don't comment their code.

------
ceautery
>> Comments, by their nature, are static.

Says who? Comments, like unit tests, and READMEs, need just as much attention
as raw app code. As others have said here, explaining what the code is doing
isn't the end goal of comments, because you can read the code for that.

I tend to use comments mainly for handoff purposes. One of my peers needs to
know what I was thinking, goals, anomalies, etc., rather than how to parse
syntax, which they can do already. Here's a random example:

    
    
        /*
         *  checkReady() starts the winston logger, which is set to catch unhandled exceptions. We don't want
         *  to do that until both the web and SMTP listeners have started, so that they can throw errors and
         *  exit the app. This is important because running on well-known ports without cap_net_bind_service
         *  shouldn't fail silently.
         */
        function checkReady() {
            if (++serverCount == 2) startLogger();
        }
    

...And whether or not I've made a bad decision here regarding startup logic is
moot. :)

------
jpalomaki
I don't remember a real life situation when I was unhappy because the code had
so many comments. Several times I've been unhappy because the developer
obviously had spend a lot of time thinking something, but did not leave any
clues about his thought process in form of comments. Especially if the code is
dense, it is not always easy to grasp the meaning.

Sometimes the lack of comments leaves you to wonder if you are looking at a
bug or a deliberate design decision. When working on projects that have
history, one sad thing is that usually everything else gets lost over time
except code and comments. Design docs, issue trackers, emails, commit logs -
all gone when companies change, code is moved around etc.

My general instruction would be that if you are thinking if you should write a
comment, then write it. Writing a comment takes no time at all and it is easy
to remove later. Coming up with the same insight that would be captured by one
line comment may take hours when somebody else is looking the code 12 months
later.

~~~
jordanhudgens
Yes, the problem that I've found is that I've taken over legacy applications
(several times), where the previous developer wrote comments/instructions for
how to work with a method. And I wasted countless hours trying to follow their
instructions, just for it to turn out that they had changed the method and
never updated the comments. So the time wasting component can work both ways
in my experience.

If that were an isolated incident I would blame it on the individual
developer, however it's been a constant trend in the apps I've taken over
through the years.

------
jpatte
I think the author missed the opportunity to show how choosing better
identifiers for his example would have eliminated the need for comments
immediately. Also notice how his comments were actually bad from the
beginning: it said the method returns something even though it doesn't.

Example:

    
    
      def printPlayerLineup(playerPositionByNames)
        batOrder = 1
        playerPositionByNames.each do |name, position|
          puts "#[name} bats #{batOrder} and plays #{position}"
      	batOrder += 1
        end
      end
    

There are also a few tips to give about how to pick good names. For example if
you expect an array of player names the argument should be called
`playerNames`, not `players`. Another example is function names should always
start with a verb.

Also, if you end up writing comments just to specify types, consider using a
statically typed language instead.

~~~
NateDad
What am I allowed to pass into this function? a hash? a list? To me, player
position by names sounds like a hash of name:position. Your code assumes the
input is in bat order, but doesn't say that anywhere (and how does that work
with a hash?). This is why you need comments.

------
AlexeyBrin
At a minimum, unless it is a trivial piece of code (like a few lines), you
should comment about the purpose of a function and usage.

Here is an example of how the _old school_ numerical analysts documented
purpose and usage of their code (the short variable names are a historical
artifact) [http://www.netlib.org/lapack/explore-
html/d0/db8/group__real...](http://www.netlib.org/lapack/explore-
html/d0/db8/group__real_g_esolve_ga3b05fb3999b3d7351cb3101a1fd28e78.html#ga3b05fb3999b3d7351cb3101a1fd28e78)
For the more curious, this is a Fortran subroutine that solves a linear system
of equations.

------
thr0waway1239
One of the best ideas I saw here on HN was someone saying that they will
mentor their employees to add comments to their code exactly under one
condition: you add a comment above it explaining why the comment below needs
to exist.

That's a pretty interesting way to enforce some discipline in the commenting
process, basically by adding some necessary friction into it (while also
keeping it generally simple).

Curious if there are people who have tried this approach or a similar system,
and how it worked out?

~~~
jhugg
Ugh. Why the comment hate on HN?

Reading code, it’s pretty astoundingly rare that I look at code without
comments and think, man, this code is so self-explanatory! Conversly some of
the best code I’ve ever read has comments that clearly explain what is
expected, why the code works this way, and what other parts of the system use
it.

~~~
xyzzy4
Maybe it has to do with the language? If you read code in an easy language
like Java, it's usually self-explanatory.

------
methyl
One more justified case for commenting is in my opinion when you have to work
around some bug or specific behavior of 3rd party library by doing unusual
construct.

If you comment that part, it will be much easier to read the code and avoid
changing such construct. I know it should be covered by tests anyway, but it
will save some time for your coworkers.

------
zck
Names are exactly as easy to not change at comments are.

------
Walkman
I really like the way Robert 'UncleBob' Martin put it: "Every comment you
write is a failure to express yourself well in code."

~~~
NateDad
How are you going to express these in code:

"We have to trim the last character because this third party library we're
calling has a bug that doesn't handle null terminators"?

Or "we have to continue to support the old-style url for backwards
compatibility reasons"

or "we're dropping down to assembly here because it's 100x as fast as the
naive solution"

or even "This function ensures the returned string ends in a line return."

~~~
Walkman
First three are "why comments" so they are good. The fourth is not a comment.
It should be clear from the code what it does.

~~~
NateDad
You shouldn't need to look at the implementation of a function to know it's
basic functionality.

~~~
Walkman
So name your function "ensure_line_return"!

------
vesak
I've felt that business requirements tend to be the sort of thing that benefit
from code comments. Because too often you don't have time to create the whole
machination that is required to fulfil some arbitrary business rule.

------
longsangstan
I see lot of people using the argument "code should be self-explanatory so you
don't need comments". But even if the code is clear and self-explanatory, isnt
it still faster for people to read plain english?

~~~
marxidad
Ideally, the code should read as close to plain English as possible. There's
still a trade-off between specifying it in one place and synchronizing two
pieces of text so that they basically say the same thing.

------
placebo
The point is not whether to comment or not - it is just to do whatever it
takes to make what is happening on every level more understandable whenever
there's the slightest doubt that it might appear unclear to anyone else
(including the future you). It doesn't matter if it requires rewriting the
function, adding a link to more in-depth documentation or populating the code
with ASCII art of wild flowers - just make sure that the next person that has
to understand the code won't curse you...

------
sebastianconcpt
The point made in the article is based on an example that violates good
Separation of Concerns. Also focusing on _why_ induces developers to justify
themselves the reasons to write the code and assume any reader knows all the
assumptions of the environment. This trend will strongly disencourage code
exploration and keeps newcomers in the outer side of the wall. A good
alternative would be to have a combination of 1. good separation of concerns
2. good method/function name and 3 comment with focus on _what_. If you do
this consistently your app would be really friendly to newcomers and even to
your future self because when taking a look to it 2 years later, your code
will tell you the name of an action followed by a human description of what it
does _without forcing_ you to read the rest of the code and reverse engineer
it to answer what it should be a simple question. Also you scan code through
the app faster if you need to read less to understand what's all about. Most
people don't see this because they are too immersed in the set of assumptions
that a given project has, but time proves they would be rather focusing on
_what_. There is a secondary benefit on doing this, it will slowly make you
write better method and argument names, so it will me more often than not that
your code will need comments at all.

------
alkonaut
It would be really cool if whether the method takes an array or a hash table
could somehow be part of _the code itself_ , and if the function is updated
but not the callsite an error is shown?

Alternative title: "Should I use a type system?"

Sarcasm aside: comment anything non-obvious, and make the non-obvious things
as few as possible. It's always better to have two lines of overly obvious
code, than to have one line of opaque code plus one line of comment.

------
cestith
I think of comments similarly to footnotes and embedded notes in prose
writing. If there's something I can explain in the normal flow of writing, I
do so.

If I have to refer to some research, a bibliographical reference, some outside
documentation about data formats, or some special business rule which impacts
the case I make a note. They are for asides, deeper context, and outside
references.

Don't use footnotes to explain the paragraph. Use them to explain the context
in which the paragraph is to be understood. Likewise, use code comments to
explain the context for the code.

Many of my comments are an example record for some legacy data format. I don't
write a comment for every line of the parsing routine. I give the example
record and the code. Many are also notes about an RFC or standard, down to the
paragraph, and where my implementation ignores some obscurity in that or which
way I interpret some ambiguity in it. Why that standard was chosen rather than
a competing standard, though, is often more suitable for the developer doc /
README rather than in the comments themselves.

------
fisherjeff
This may sound tedious and strange, but I've learned to comment nearly every
line I write. I think the cognitive load while skimming is much lower, but
MUCH more importantly, the process of writing them is a very valuable
perspective shift. It forces me to look at a block of code more holistically,
and as a result I tend to catch most of my bugs while writing comments.

------
vetler
How to create readable code that explains itself should have more focus. It's
not just about naming classes, methods and variables, but also about
structuring your code. It's quite possible to create a method with the perfect
name that is over nine thousand lines long and difficult to understand.

This can be very subjective, but code complexity metrics can help identify
problem areas. I find that areas with high complexity often benefit from
refactoring into smaller pieces making it more readable and self explanatory.

If you can't structure your code to explain itself, perhaps commenting isn't
such a bad idea, at least it would be a record of your thoughts at the time,
until someone else comes a long and hopefully cleans it up.

~~~
lsaferite
Just to echo what has already been brought up here, sometimes it's not the
_what_ that is important, but the _why_. Reading the code is unlikely to
explain the why for quite a few complex things.

------
tyleo
While I understand that comments can make it more difficult to understand
code, I have frequently seen this advice taken too far. What is clear to the
writer may not be clear to readers so they may avoid commenting complex code
they have been working in for awhile.

------
rkangel
This article completely omits mention of 'why' comments, and only talks about
'what' comments.

I can just about accept that in a sufficiently descriptive language that what
the code is doing can possibly be made clear (in practice for things like
embedded C, this isn't actually true). But no code, however well named, can
ever tell you WHY it is doing what it is doing. Those code comments are
invaluable.

They can range from the trivial explanation of a corner case bug as the
rationale for an otherwise pointless looking bit of error checking, to
discussing a system requirement when explaining the implementation choice for
a whole module.

------
gotofritz
Beginners tend to write long comments explaining what the code does, then as
they progress the comments get shorter (because they can read the code more
quickly) and eventually come the realisation that

// gets bear count

function getNumber() ...

is not as good as just

function getBearCount() ...

Places where comments are still useful, IMHO:

\- complex or clever code; e.g. when I use shift for division by 2, that tends
to confuse some coders, or regular expressions in javascript (for some reason
JS devs seem scared by regexp)

\- strange requirements or bugs or other reason to do something in a weird way

\- other places why it may not be clear what I am trying to achieve

~~~
Nadya
>\- complex or clever code; e.g. when I use shift for division by 2, that
tends to confuse some coders, or regular expressions in javascript (for some
reason JS devs seem scared by regexp)

I've found I've never had to use a Regex in Javascript yet. Also I don't think
anyone enjoys reading Regex. Writing it is a lot easier. :)

Reading `/2` or ` * 2` is more intuitive than `<< 1` or `>>> 1`. Although I
learned a new code obfuscation technique! ;) [0]

Testing 2^39 and bit shifting is negligibly faster. At lower values (2^4) it
is equivalent. For any multiplication/division by a higher power of 2 (2^2,
2^3, 2^4) they become equivalent in speed.

    
    
        549755813888 * 2 x 1,526,678,336 ops/sec ±0.67% (97 runs sampled)
        549755813888 << 1 x 1,562,645,566 ops/sec ±0.26% (99 runs sampled)
    
        549755813888 * 16 x 1,552,125,291 ops/sec ±0.33% (100 runs sampled)
        549755813888 << 4 x 1,530,867,164 ops/sec ±0.35% (98 runs sampled)
    

This seems like a case of "being too clever" by trying to optimize something
that the compiler can optimize itself.

~~~
gotofritz
There was a time when it made sense, but now I agree it's rather pointless

------
eddd
1\. Comments should be subject for tests (for example:
[https://docs.python.org/2/library/doctest.html](https://docs.python.org/2/library/doctest.html))

2\. They should describe the purpose of the code in general not the quirks in
the code

3\. The exception rule is when the code can't be self-explanatory. Hacks are
undesirable, but in real life you have implement them sometimes anyway - then
comments are necessary

4\. Docstrings in everything are wrong, the code itself is a documentation.

------
kzisme
I've always used comments on adverse behavior, or to remind myself/whoever
reads it later about something I got stuck on.

If you take the time to refactor a function it takes no time at all to edit
the block comment above the code.

Lately I've been caring less about how long the name of a function may be, and
I've found it much more helpful when looking back at code I've previously
written.

------
theandrewbailey
How not to comment:

Put in a bug tracker number, description, and your name, and end up with a
comment much larger than the code actual change. Also comment the end of the
change.

DO NOT REMOVE! Almost all web analytics tracking tags have these. Do not
remove? I do that all the time. Those messages are probably there for brain
dead people, but it doesn't stop them either.

------
loupax
This reminds my of my own pet-peeve when it comes to good practices being
abused:

DRY: DRY in the sense where "I have three nested ifs, but to avoid I have to
compare against this variable three times so my code now is simpler. RIGHT?"

------
xaduha
What is really annoying is that there are many Github repos without a useful
README.

------
wildpeaks
A good rule of thumb is that code shows "what" it does, comments explain "why"
(when it's not obvious).

------
exprA
I don't see any of the functions returning any lists. They do produce some
output, though.

------
vacri
It's curious that the answer to "people don't have the discipline to update
comments" is "develop the discipline to code in a way that avoids comments".

------
joesmo
This is _horrible_ advice from a lazy coder. I tried it for a couple of years
and now I have to go back and figure out my old code. Sure it's doable because
it's good code, but it's an absolute waste of time that could have been
avoided with comments. Let's say it takes me 5 minutes to figure out 10 lines
of well-written code after some time has passed without comments or 5 seconds
with comments. Which one is better, especially when you have to figure out
hundreds of lines of code?

------
xyzzy4
Generally you should only comment if your manager really wants you to,
otherwise just write clear code and don't comment.

