
My mission to (almost) eliminate code comments - davethedevguy
http://www.davejsaunders.com/2020/06/10/eliminating-code-comments.html
======
Jallal
Actually, there are many cases for wich I believe the comments are useful:

\- When you have some "complex" technical code. Using natural language is
sometimes the most effective way to explain what is done by the related code.

\- When you deal with some business logic that can become weird an one point
(process all these things in some ways, excepts these ones, weird edge cases,
etc.). From a developer perspective, it does not always make sense, but it's
always useful to have some background explaining why the code has been written
in such way.

\- When you have to consider history on a large code base. I know that people
on HN mostly work on new shiny projects, but with legacy applications, you
have to deal with all the bad/incorrect choices that were made before, and
refactoring is not straightforward and is costly. I'm not saying it should not
be done, but sometimes, you can work on it only in an incremental way.
Comments allow you to add some perspective on the code (explaining the reverse
engineering you've done, the initial assumptions, why they turned out to be
incorrect, what should be done to improve the situation, etc).

Also, I disagree with the facts that comments are born out lazyness. "Lazy"
developers don't bother writing comments. Actually, there don't care, and most
of them do not even realise that at some point in time, someone will have to
browse, read and understand their code. The only kind of comments I've seen
from such people are "commented code", because "it might be useful" (it never
does).

I see comments as a way to engage a (one way) conversation and provide useful
and meaningful information to a future code maintainer. Sure, such comments
should not clutter the code, be relevant and meaningful, stay up-to-date but
it's - as many other things - a skill that require time to get it right.

Looking to eliminate all of those is not an approach that I think should be
followed (but it's just my opinion). Focusing on allowing the code to be
understandable by an hypothetical maintainer in the future is more relevant.
If extra comments have to be added, so be it. These are tools, not ends.

~~~
nailer
> When you have some "complex" technical code. Using natural language is
> sometimes the most effective way to explain what is done by the related
> code.

Totally agreed here. There's some code in underscore that recursively copies
strings as a way of writing ' __ __ __ __' because it happens to be fast.
You'd think it was really weird if it wasn't marked as a performance
optimisation.

> When you deal with some business logic that can become weird at one point
> (process all these things in some ways, excepts these ones, weird edge
> cases, etc.). From a developer perspective, it does not always make sense,
> but it's always useful to have some background explaining why the code has
> been written in such way.

That's the 'why' addressed explicitly in the article.

> Also, I disagree with the facts that comments are born out lazyness. "Lazy"
> developers don't bother writing comments. Actually, there don't care, and
> most of them do not even realise that at some point in time, someone will
> have to browse, read and understand their code.

> The only kind of comments I've seen from such people are "commented code",
> because "it might be useful" (it never does).

It sounds like you largely agree with the article. Save comments for 'why',
you want to eliminate meaningless comments.

------
axegon_
I have mixed feelings about this. I think it depends on the project you are
working on. If your codebase can be packed into a few hundred lines of code,
with nothing fancy or complicated and no code is being injected from
elsewhere, then the author is absolutely right. Documenting what a function or
a method does should be sufficient and imo you should do that in all cases,
just for the sake of making it easier for new developers to jump into the
project if they prefer using some fancy IDE. However if your codebase is
composed of several million lines of code(like a lot of the ones I work on),
things change. Using readable names is a perfect general advice but eventually
you end up with complex logic, which is not necessarily the result of some
developer who just wanted to get a task out of their way but could be as well
a result of "business needs this by Monday, 3 weeks ago" or simply some mind
boggling edge case which needs to be handled. In which case, adding some
inline comment with an explanation as to why something is there and ideally a
link to your ticketing system can be a life savior. I'm far not a fan of
things like:

// Increment counter by 1.

counter++;

You should never do that unless you are studying programming and you have been
required to explain every line of code along the way(though I don't know why a
professor would ever want that, certainly no one ever asked me to do stuff
like that).

~~~
echelon
> Documenting what a function or a method does should be sufficient and imo
> you should do that in all cases, just for the sake of making it easier for
> new developers to jump into the project if they prefer using some fancy IDE.

Document _nothing_ until you have to do something weird and unexpected.

An example might be:

    
    
        // NB: We're downsampling to 22khz because we found that the 
        // multi-speaker model chokes on higher sample rates.
        source = downsample(source, 22000)
    

Or:

    
    
        // We don't perform internal retries here because our clients 
        // handle that themselves when we respond with a 429. 
        retryCount = 0
    

Or:

    
    
        /* Firefox renders this mistakenly, and overflows the 
           element. We opted to add padding to account for this 
           difference. See BUG-4282 for more details. */
        padding: 0 0 3px;
    

This strategy captures all of the things that you'll forget, but leaves
nothing that might go stale. In essence, only the things of value that
couldn't be intuited from the code itself.

Do not leave any other types of comments! Ever! Not even method docs. (The
only exception being if you're writing a library and want to generate a
documentation website).

You'll find that you start writing code that is like poetry. Structured,
naturally intuitive, and easy for others to read. You'll become a better
programmer, and your code base will improve dramatically. Comments, of course,
will never go out of date.

~~~
axegon_
> Do not leave any other types of comments! Ever! Not even method docs.

Have you ever looked at a very large project(blue whale as I'd like to call
them)? In 10 years time, 90% of the people who have worked on it initially
will be gone from the company (or stopped contributing if it's an open source
project). You are making everyone else's life a nightmare. To my mind the one
project that got it bang on is postgres. It is by no means a library and the
community's approach is perfect. Open up any of the source code files at
random and you'll see what I'm on about. Just scrolling through the code and
comments once will be enough for you to figure out exactly what is there and
why.

~~~
echelon
> Have you ever looked at a very large project

> You are making everyone else's life a nightmare.

I work on code touched by tens of thousands of other engineers. In my
experience, code without comments is typically structured, easy to read, and
does exactly what is written. Code painted top to bottom with comments tends
to be muddied, confusing, and more junior in nature.

The shape of solutions is common. You're not reinventing the wheel with every
new project. Engineers are familiar with the design patterns, frameworks, and
algorithms you use, so you don't need to force a context switch to point them
out.

You can use the symbols themselves as a form of documentation. Instead of
having an entire algorithm inline, individual queries or processing steps
might be put into their own self-documenting methods:

    
    
        verifyMarkdown(article_rating: &Rating)
        upsertRating(article_rating: &Rating, author: &User, transaction: &Transactor)
        publish(article_rating: &Rating, transaction: &Transactor)
        enqueueSubscriberNotifications(author: &User)
    

Small pieces of code might not require a functions to wrap them, but by naming
small units of behavior, you can communicate your algorithm step by step
without comments.

This is only one type of communication technique you can use. There are
bountiful ways to improve your clarity.

I apologize if my examples are obtuse. It's late.

~~~
axegon_
OK, good points, but my argument stands in most cases: It doesn't matter how
experienced a developer is. You'll rarely see anyone as pedantic as I am when
it comes to conventions, structure or organization, but there have been
multiple instances when I've had to cut corners to meet some deadline. I work
on an enormous projects with few developers. Say we all decide to go full Eric
Cartman tomorrow and call it quits. Guess how long it's going to take someone
else to work their way through 8 years of development without a single
comment? My bet - they would keep hitting rocks day in and day out.

In the case of thousands, the likelihood of everyone leaving at the same time
is much lower, but I'll go back to my postgres example, which I genuinely use
as a benchmark as far as code goes. If everyone abandons it today for some
reason, everything is so well thought out, well structured and documented that
new people can jump in right away and the development won't be slowed down
dramatically, granted that the new developers follow the current process.

------
baby
Urg, I strongly disagree with this take. First, comment your damn code if you
work with others so that they don’t waste time reverse engineering your code.
Sure use better variable and function names but do not create a function that
can be inlined just to replace a comment... You’re adding abstraction and
making your code less clear (which is not what you intended).

~~~
rootlocus
Compilers can inline functions. Functions can be tested, reused and composed.
Comments usually rot.

~~~
baby
It’s about code clarity not optimizations.

------
lultimouomo
Pretty much the opposite advice than [http://number-
none.com/blow/john_carmack_on_inlined_code.htm...](http://number-
none.com/blow/john_carmack_on_inlined_code.html)

~~~
saagarjha
I’m curious if anyone has tried some sort of editor plugin that, instead of
doing something like “go to function” when you encounter a call, instead
temporarily inlines the code into what you’re reading so you’re not jumping
around. Seems like this might be the best of both worlds, with abstractions
hidden but instantly available to scrutinize when necessary?

~~~
lentil
Visual Studio Code has a "peek" operation that does something like this. It is
indeed quite handy.

[https://code.visualstudio.com/docs/editor/editingevolved#_pe...](https://code.visualstudio.com/docs/editor/editingevolved#_peek)

~~~
LandR
Available in the full blown Visual Studio as well.

------
AdrianB1
Just my 2c:

\- the theme is to move the comments in the code by using variable names and
function names that tell a story. Not a bad idea by itself, but nothing
special there either.

\- moving a simple one-liner arithmetic operation to a function that is stored
somewhere else is a complexity increase that is hard to justify. Every line of
code can be hidden behind a function, is that productive, acceptable and lean?

\- not trying to be picky, but for free shipping I would prefer to do
shippingCharge = 0 instead of that because that is what you want to do.

And a question: if the comments are out of the code (where they are mostly
contextual), what kind of documentation is left behind for the support team?
In my world the support team has encounters with code written 10 years ago by
people no longer around, they know high-level what the code is doing, but the
devil (bugs) is in the details.

~~~
davethedevguy
I agree entirely that this isn't anything new, I hope I didn't imply it was.
This is simply my own reflection on how to improve my coding style.

> "Every line of code can be hidden behind a function, is that productive,
> acceptable and lean?"

I've seen some advocate for that exact thing, but I certainly wouldn't go that
far. I don't think we have to have one or the other, there's a middle ground
in my opinion.

If the code requires a comment to explain it, then maybe a well-named
method/function is a better option. If the code is obvious in its own right
(looping over a collection to add 1 to everything, to use a dumb example) then
I don't think abstracting it is justified.

I certainly don't have any objection to single-line functions to add
readability per-se. (with the caveat that a compiler would produce the same
result either way, or otherwise the performance of another function call isn't
an concern. I'm talking purely about readability here)

------
wastedhours
How strange - I've always found comments useful. As I'm not a developer but
sometimes have to edit different files in the code just to enable/add in new
parameters (so engineering resource isn't needed to be planned in), it's
always been helpful to have explicit guidance in the code as to what I'm
reading is doing. Still get a code review afterwards anyway, but minimises
risk.

If you're expecting non-developers to sometimes interact with your code or to
help with troubleshooting, in-line comments will always be appreciated.

~~~
biddlesby
This is a great point. You might take a different approach depending on when
you expect your reader to already be proficient in the language or the
framework, compared to whether a non-developer might be reading the code.

One argument against these kind of comments is that they aren't the right
place to teach somebody a programming language. However I can definitely see
cases where they are justified.

------
tluyben2
To give some 'yes, that's maybe great, but is it practical?' feedback; I often
work with (bigger) companies where code reviews fail if you don't have:

\- comments, the more the better \- design patterns, the more the better

Even if absolutely useless; the over-architecting just for over-architecting
sake is quite... Not only does it take a lot of time to actually reuse the
code (a lot/all of those patterns are conceived for reusing code in the first
place but in reality it takes people a long time to get into them and the
gains are not convincing aka I see people just plonking together a little
microservice in a fraction of the time with Node and (virtually) no design
patterns to replace (parts of) the java/c# monster that does the same thing
just to make the deadline or to skip diving into the sea of blackness), but
the comments really do not help at all; they are just there to have comments.
And the design patterns (+ the way they are used) are considered standard
(they are, but not for young people who have no degree and no experience
applying them, or maybe even knowing they exist).

Still, without all that, the merge requests are being declined until you pop
in random drivel 'for best practice'.

I am a fan of terse but readable code these days (it changes somewhat); the
design patterns are more and time wasting (to me), especially when enforced in
this way (but I think everyone will agree with that anyway).

------
smabie
This isn't a good idea. And his functions, well... they're gross. You're going
to replace

    
    
      orderCost = orderCost - shipping;
    

with

    
    
      ApplyFreeShipping();
    

Now you've violated referential transparency, introduced some unnecessary
global and mutable state, and not really made anything clearer.

Let's take his other example:

    
    
      var outstanding = GetOutstandingOrders();
    

Into

    
    
      var allOutstandingOrders = GetOutstandingOrders();
    

Please for the love of god, no. Variable names should be short, and in my
controversial opinion, as short as possible. Long variable names actually make
code more difficult to understand, not easier. Rob Pike talks about it in the
Practice of Programming, and it's a common tenant among APL/J/K programmers as
well.

Here's how I wish programs were structured:

1) Make your code as terse and dense as possible so you can see as much of it
at one time as possible (see code written by Arthur Whitney). 2) Make your
variable names abbrevations or acronyms, like instead of 'convertInt', call it
'ci'. 3) Comment every function and keep each function to only a couple lines.
4) Because your functions are so small and dense, you'll never need to modify
them, only throw them away. 5) Bam, your comments and never out of date
because the functions you're writing never need to be modified, only deleted.

Unfortunately, most programming languages don't give you sufficient power to
do anything in a couple lines. Which brings up the question, why don't we
switch to those that do? Honestly, J or K would be totally usable for the vast
majority of programming problems.

~~~
chimprich
I agree that variables names should be short, but not "as short as possible".
They should be as short as possible while remaining unambiguous and avoiding
loading short-term memory.

"allOutstandingOrders" does not look to me like a long variable name.

> Make your code as terse and dense as possible

I really hope I never get to work with any code you've written.

> Make your variable names abbrevations or acronyms, like instead of
> 'convertInt', call it 'ci'

I'm starting to think this comment is satire now.

If I have to read the comments on a function or variable to figure out what it
does then my productivity is going to be absolutely kneecapped if I'm a
newcomer to your project.

------
TedDoesntTalk
> The majority of comments I write are a born out of lazy coding

Then you're doing it wrong. Comments can be used to describe your thinking
process, an algorithm, or explain esoteric code. I write comments with the
target audience being people who inherit my code 5 years after I've left the
project.

I'd argue that lack of comments on large projects may be an indication of an
immature developer.

~~~
boffinism
> Then you're doing it wrong.

I... I think he knows that. I don't think he was ever going to say "The
majority of comments I write are born out of lazy coding, so that's perfect."

~~~
davethedevguy
Yes, exactly this.

The reason for writing this article is that I _know_ I often do it wrong.

I'm trying hard to make sure that the comments I do write add value to future
readers of the code (including me), and are not just be a by-product of
another deficiency in my coding style (such as poor variable naming, to use
one example).

------
tralarpa
Concerning the example with the outstanding orders, I think the main problem
in practice is not so much the poor naming of the variable, but the lack of
documentation of the called function ("Process" in this case). I could live
with the variable name "outstanding", but the IDE should better show me a good
explanation of what the function "Process" is doing when I point with my mouse
on it.

The example is also a good example why type declarations are so helpful. Just
by looking at the lines "var outstanding = GetOutstandingOrders()" or "var
allOutstandingOrders = GetOutstandingOrders()", I could not tell whether the
function is returning a list of outstanding orders or whether it has a side
effect (reading the outstanding orders into a buffer) and returning a boolean
indicating that there are outstanding orders.

------
sgt101
Every programmer comes to believe that comments are the symptoms of bad code
at some point in their development. Many, but not all, of them realize that
they are wrong quite quickly afterwards.

Comments aren't a crutch to be used because of an impairment , they are
helpful support in the face of the challenges of diverse technologies, poor
documentation and difficult communication over time and space. Importantly
they are integrated into the code base and are aimed at a very specific
consumer - future programmers. Future programmers who may include you!

------
LandR
I worked in a place where if you commented your code you would fail the code-
review.

I had a mate who worked at a place where the code once it was checked in was
ran through a processor that deleted comments!

~~~
davethedevguy
Wow! I'm not sure I'd go as far as to eliminate comments entirely!

My aim is just to write _less_ comments, so the ones I do write mean something
and aren't just noise.

------
seanwilson
To counter the negativity, this was a good post and I agree with it.

The example with the unneeded comments for conditionals and the one that
explains "what" a function does is something I see even senior devs do all the
time.

I think a lot of replies here aren't reading the article or are focusing on
nitpicky examples.

"Comment your code!" is a deeply ingrained piece of advice people throw around
without the warning that a lot of coders write comments in place of good
function names and variable names.

------
l0b0
A useful way to think about it is that _names are basically comments, but only
names can be looked up by an IDE._ When looking for a frobnicator I can find
it trivially if there is something _named_ "frobnicator" or anything similar.
If there is a _docstring_ mentioning frobnication (maybe with some
"alternative" spelling or other word form like a verb when I'm looking for the
noun), on the other hand, that's _much_ harder to find. And once I find it, I
still have to locate the _actual frobnicator somewhere near the comment._ Even
this is the ideal case, where only one comment mentions frobnication. What if
it's a common word? Now the chance of finding the right thing in a reasonable
time goes _way_ down if it's not named properly.

------
zwaps
The author has a point that comments may be superfluous when going through a
code line by line.

However, that's not the only sort of code-reading. Comments can sometimes be
better to get an overview of a complex program. Not if it is your own code,
sure, or even in a code-base you work in. But faced with a huge amount of
foreign code, over-commenting can be very useful (at least for me).

This should not be an excuse to write bad code - here I agree with the author.
But given that, I see little downside in good comments.

It's an extremely challenging task to think about how others would perceive
our coding. Perhaps the reader isn't familiar with a technique or function
that seems obvious to you? It's the same as trying to give a lecture on a
subject. Pedagogically, it's preferable to have more comments than less.

------
eeh
This is the approach advocated for in
[https://www.goodreads.com/book/show/3735293-clean-
code](https://www.goodreads.com/book/show/3735293-clean-code) .

I like it, but I know some language communities don't.

------
thiht
I'm not so sure about converting

    
    
        if (customersFirstOrder) {
            // Apply free shipping
           orderCost = orderCost - shipping;
        }
    

to

    
    
        if (customersFirstOrder) {
           ApplyFreeShipping();
        }
    

Does `ApplyFreeShipping` work on global state? How do we test it? At the very
least it should be something like:

    
    
        orderCost = ApplyFreeShipping(orderCost, shipping);
    

which has advantages over the first version but is not necessarily better. The
suggested version is just awful though.

------
partyboat1586
Terse variable names are easier to read if you're doing anything non trivial.
I only need to understand what it is once, not every time the symbol appears.
If the abbreviation isn't clear then add a comment when it's declared. The
comment is just as likely to go out of date as the variable name itself so
there is no cost to the comment.

------
LandR
If you don't like to see the comments hide them in your IDE. Most decent IDES
let you set the background and foreground colours based on the code.

i.e. I have comments for type /* */ and // set to be grey on a slighgly darker
grey so they are pretty much hidden (as they are useless most of the time).

~~~
goto11
IMHO this is the worst of both worlds. Comments very easily get out of sync
with the code then.

I prefer the comments to stand out more than the code. Also helps eliminating
useless filler comments since they are so noticeable. _If_ you have comments,
they should be important and helpful.

------
alfiedotwtf
After seeing Damian Conway‘s training courses teach this, I’ve tried to shoot
for this style ever since.

It definitely lowers cognitive load and “feels” better, but I still feel bad
when adding function call overhead just for style (maybe the compiler is
actually that smart and there’s no hit)

------
Supermancho

        orderCost = orderCost - shipping; // Apply free shipping
    

Now it explains why.

~~~
nailer
The author addresses this in the article.

------
spderosso
Related article (published in 2017):

[https://testing.googleblog.com/2017/07/code-health-to-
commen...](https://testing.googleblog.com/2017/07/code-health-to-comment-or-
not-to-comment.html)

------
nesarkvechnep
I like how the code in (almost) all the examples can lead to horrible side-
effects.

~~~
saagarjha
Only if your function has side effects that the name doesn’t imply.

------
gremlinsinc
Does this include doc blocks? I mean a lot of ide's have addon info they glean
from those, as well as some api-generators use annotations to generate them,
and same w/ phpunit.

------
taylodl
There I was all ready to get my pitchfork out and then I read the article and
damn! These are good points!

------
ykevinator
Comments are great for teams and your future self but your point is well taken

------
tuananh
i like the idea in general but the example is quite awful.

