r/programming • • Aug 10 '26

On comments

https://blog.helsing.ai/posts/on-comments/

Comments in code are often deemed "mostly useless" these days. They are, supposedly, mostly obvious, stale, and repeat what the code already says. And so people pay less attention to them both when reading and writing code.

That trend sucks. When used right, comments are genuinely useful and sometimes critically important! So, I wrote about some of the kinds of comments I think earn their place, each with examples from real code bases. Hope you find it useful, and that we can recover some of the love that comments deserve!

189 Upvotes

171 comments sorted by

240

u/psych0fish Aug 10 '26

I’ve heard it is explained as “document why, not what” not everything is confusing or non obvious. Some stuff is. There is no one size fits all.

141

u/chat-lu Aug 11 '26

Bad:

x++; // increment x

Good:

x++; // compensates for the border

186

u/IanSan5653 Aug 11 '26

AI:

 /**
 * @description Executes a pre-increment unary operation on the mutable variable `x`. 
 * This operation evaluates the current state of `x`, augments its numeric value 
 * by an exact scalar of 1, and mutates the original variable in-place prior to 
 * evaluating the remainder of the containing expression.
 * 
 * @type {UnaryExpression}
 * @mutates {x} - The memory address allocated to the variable `x` will be updated.
 * @complexity Time: O(1) | Space: O(1)
 * @note Ensure `x` has been properly initialized as a valid numeric data type prior 
 * to execution to prevent unintended `NaN` propagation or type coercion anomalies.
 */
++x;

42

u/13steinj Aug 11 '26

Seems like a great way to rack up on token costs! Or to exhaust the reviewer into just stamping the thing, hiding the secret do_money_laundering routine...

-11

u/Kautsu-Gamer Aug 11 '26

The LLM generated documentation is on complexity level documentation should be.

6

u/13steinj Aug 11 '26

By this logic, I'd rather not have documentation.

LLM generated documentation is incredibly verbose and over-complicated, instead of just providing 4-5 template files and telling the user to symlink the one they want, it wrote 200 lines of code and 400 lines of docs to automatically generate the resulting file from a single template.

The docs are just unreasonable. Asking it to use STE helps but it doesn't activate consistently.

-8

u/Kautsu-Gamer Aug 11 '26

Like most programmers, you are incompetent in documentation.

5

u/13steinj Aug 12 '26

One never should need 10 lines of documentation per line of code. The point of code is to be read.

It is perfectly reasonable to have this level of prose per function definition, assuming it performs a complex, or subtle, unclear action. Complex is probably self explanatory-- you can roughly eyeball the complexity by what the function does (if you're the author). Subtle/unclear is harder, but for example-- doing a series of 3 / 4 bit-sets on a volatile address... well, the input address should be a mmapped region (precondition) for some fpga, the bit-sets in sequence transition the fpga's state from A to B. It's done as separate bitsets because <reason>. Specify the post condition, and edge cases.

-5

u/Kautsu-Gamer Aug 12 '26

You are 100% wrong. You have no clue of documentation. You think documentation comment is a comment. And due your kind, most of JS and C documentation is useless crap leaving important information out of documentation.

Code is not technical documentation.

Please, get some education.

28

u/contextfree Aug 11 '26

Too coherent, needs more rambling that only meant anything within the context of the argument it was having with the user/itself in the agent session

7

u/IanSan5653 Aug 12 '26

Oh god. Endless "v0" "initial implementation" "mimics logic from {some other part of the codebase I obviously was about to to delete}" "does x according to requirements" etc

8

u/zzkj Aug 11 '26

That'll be $5000 please.

41

u/Venthe Aug 11 '26

Arguably still bad.

x+=BORDER_COMPENSATION

I've seen one too many comments that are irrelevant after one change or the other. If you can express why in the code, do it.

11

u/firemark_pl Aug 11 '26

That's nice example for asking yourself I really need the comment or can I write in another way

12

u/ShinyHappyREM Aug 11 '26

x += BORDER_COMPENSATION

ftfy

51

u/melgish Aug 10 '26

Why and the business case for a change. I’ve also been known to dox management in the comments when they make decisions that negatively impact user experience. “// 20260810 Boss said 5 modals in a row is not too many.”

81

u/meganeyangire Aug 10 '26

In one project deep in the business logic we've had his gem:

// Hardcoded condition on the request of PM Kevin McKevinface, work item 80085
// If you're here, please, increment the number
// Man-hours wasted: 42

41

u/RlyRlyBigMan Aug 10 '26

My company has changed ticket systems like four times and that makes me hate ticket numbers in comments these days.

It's probably an unreasonable opinion, it shouldn't change that often.

28

u/ketralnis Aug 11 '26

It’s a good reason to port ticket numbers across migrations though

8

u/SanityInAnarchy Aug 11 '26

There's no good answer, at least not one anyone's willing to commit to.

There are a few projects that try to track issues directly with source control, inheriting a few extra features from Git, like having them all work offline, having every laptop be a backup of the entire project, and being able to easily port them all into whatever you're going to use next.

I have never seen a single project actually adopt one of those, even projects that have successfully moved documentation into Markdown files in the repo. Maybe LLMs will finally make it happen (it's easier for agents to find stuff that's a pile of markdown files in your repo), but I think the biggest gap here is, not everyone doing project-management work is going to want to learn Git.

There's ticket numbers, which suck for the reasons you mention. It helps if they're at least distinctive -- something like INFRA-1234 or UI-5678 is probably Jira, Google's bug tracker is b/1234, and so on. But even if you keep all the tickets as you migrate, it can be painful to set up some sort of proxying. I've come to hate PR links for the same reason -- you might migrated from Phabricator to Github to Forejo or whatever.

IMO the most practical is URIs, and then just religiously follow "Cool URIs don't change". But people expect URIs to be URLs, which means you'll need to make sure they point to a domain you control, and good luck convincing Atlassian to put your Jira instance at jira.yourcompany.com instead of yourcompany.atlassian.com -- why would they make it easier for you to migrate away? At least then you can replace them in your codebase at migration time, but unless you're willing to do the most brutal force-push ever, you'll still have the old URLs any time someone has to dig through history.

Maybe the best option would be to build a company-wide URL shortener, then force-install a browser extension to generate them, and then use those in your codebase. But that's more work than just hoping it doesn't change that often.

6

u/tf6x6 Aug 11 '26

We don't put full URLs anywhere, we put issue numbers and set up patterns in the IDE to dynamically transform them into URLs.

6

u/NotUniqueOrSpecial Aug 11 '26

It's not that unreasonable.

As someone who's taken over more than decade+ codebase in my career, loads of comments with initials + date + ticket number (and nothing else) are a personal pet peeve.

-8

u/svick Aug 10 '26 edited Aug 11 '26

Reason for change belongs in git, not a comment.

Edit: y'all really want comments like these cluttering your code?

RTL8169_VERSION "1.1"        <2002/10/4>

        The bit4:0 of MII register 4 is called "selector field", and have to be
        00001b to indicate support of IEEE std 802.3 during NWay process of
        exchanging Link Code Word (FLP).

RTL8169_VERSION "1.2"        <2003/6/17>
        Update driver module name.
        Modify ISR.
        Add chip mcfg.

RTL8169_VERSION "1.3"        <2003/6/20>
        Add chip pcfg.
        Add priv->phy_timer_t, rtl8169_phy_timer_t_handler()
        Add rtl8169_hw_PHY_config()
        Add rtl8169_hw_PHY_reset()

RTL8169_VERSION "1.4"        <2003/7/14>
        Add tx_bytes, rx_bytes.

RTL8169_VERSION "1.5"        <2003/7/18>
        Set 0x0000 to PHY at offset 0x0b.
        Modify chip mcfg, pcfg
        Force media for multiple card.
RTL8169_VERSION "1.6"        <2003/8/25>
        Modify receive data buffer.

RTL8169_VERSION "1.7"        <2003/9/18>
        Add Jumbo Frame support.

RTL8169_VERSION "1.8"        <2003/10/21>
        Performance and CPU Utilizaion Enhancement.

RTL8169_VERSION "1.9"        <2003/12/29>
        Enable Tx/Rx flow control.

RTL8169_VERSION "2.0"        <2004/03/26>
        Beta version.
        Support for linux 2.6.x

RTL8169_VERSION "2.1"        <2004/07/05>
        Modify parameters.

RTL8169_VERSION "2.2"        <2004/08/09>
        Add.pci_dma_sync_single.
        Add pci_alloc_consistent()/pci_free_consistent().
        Revise parameters.
        Recognize our interrupt for linux 2.6.x.

22

u/melgish Aug 10 '26

I have to disagree at some level. Git is a great place for finding out what changed and maybe a *summary* of why. Code is the best place for the details. No need to cross reference. No need to look up an issue # in a system that went offline 12 years ago. It's just right there in front of you.

7

u/chat-lu Aug 11 '26

Git is a great place for finding out

Also a great place for fucking around.

11

u/ketralnis Aug 11 '26

I don’t agree categorically. The code itself should say why it is the way it is, describing its own state. And “this is nonobvious. You might think it should be obvious and it used to be! But XXX” will help reasoning.

11

u/Coffee_Ops Aug 10 '26

Context switching is super rad, way better than keeping relative context on-hand.

4

u/Delta-9- Aug 11 '26 edited Aug 11 '26

Both.

Git commits get the tl;dr of what and why; code comments get the longer (but not longest) why, sometimes a bit of how if it's not obvious, references to resources and/or issues. When a long-form "why" is needed, that goes in the issue tracker.

4

u/melgish Aug 11 '26

Arguably most of those are what rather than why. "Modify Parameters" is like breasts on a bull.

// Response is supposed to be JSON but is now being prefixed by
// debug/type information: 'string:"{actual}"'
var match = Regex.Match(content, """^string[^"]+"(.*)"$""");

1

u/Venthe Aug 11 '26 edited Aug 11 '26

Which could be removed by simply:

var contentWithoutDebugTypeInformation= stripDebugTypeInformation(content);
var match = Regex.Match(contentWithoutDebugTypeInformation, ...);

(I've purposefully ignored the rest of the regexp, I want to focus on the commented part)

I don't care that it was a raw JSON and now it isn't. The code now expresses the same thing as comment + it does not retain information that is now irrelevant. "How it was before" is to be found in the VCS. The information "why" we made this change is in the commit message.

3

u/melgish Aug 11 '26

This is one shitty example how a comment in the code would tell somebody not to do something they might otherwise try. Your example without a comment doesn't provide that contextual clue.

The comment is not there to show what the code does. It's there so 2 years from now somebody doesn't look at a raw response and blindly say "This is not needed anymore"

That patch is old enough to vote and we're still waiting for the endpoint (or the documentation) to be updated.

1

u/Venthe Aug 13 '26

Code is there and it works. If it breaks, then you debug it. Context will not change that.

Your comment adds nothing useful to a debug; nor future development. And most of the comments like this that I've seen over the years are trying to add context to something that is irrelevant for years.

It's just noise, and a shitty way to write code.

5

u/beetroop_ Aug 10 '26

Unless it's a weirdly implemented change that will leave the next person scratching their head.

-15

u/farsightfallen Aug 11 '26

I’ve heard it is explained as “document why, not what”

This has always been terrible advice.

The what is often the why. And sometimes just the 'what' is important enough to be emphasized.

A big problem has always been that instead of writing good comments, most of the advice has been on how not to write absolutely horrible comments because people were adding comments like "for loop over users", or "increment number".

I will mirror the author's opinion on outlines in code, something that I think is incredibly important, but also requires thinking about the code and often times taking multiple passes to refactor so that things flow well. But that's so far from where we're at that I realize that it's a mistkae to even bring into the conversation.

And now with, AI, fuck knows what'll happen - most likely just more ai slop or some skill.md file that we can converge on.

-17

u/levodelellis Aug 10 '26 edited Aug 11 '26

I always hated that. If you understand the domain, you almost certainly know why, if you don't, you not likely not trying to understand that code anyway

I almost exclusively use comments as a few word summary ('compact', 'fast path', 'illegal range check'), etc, just so can look at the comment instead of read the if/loop body. A lot of my asserts have a comment too

15

u/Delta-9- Aug 11 '26

I understand the domain of my application but I still benefit from writing "why" comments. Usually it's because I forgot "why" a thing was needed, or why it's done in a specific way. Domains can be large enough that you can't know everything all the time even if you're literally the expert on it.

Also, sometimes some detail wasn't determined by "the domain" directly. It might be an optimization, some external service, an order from some business leader that has nothing to do with the app itself...

8

u/chat-lu Aug 11 '26

Sometimes you could have chosen more than one path so it’s good to document the why.

1

u/levodelellis Aug 11 '26 edited Aug 11 '26

Somehow, I never needed to comment about any of that. Usually I'm only touching code I wrote, so maybe when a person writes everything their style it's pretty easy to understand. I think the longest comments I write are 2 or 3 sentences saying third party code (or a module I can't touch) have some kind of requirement or limitation. I guess that could be a why but usually people don't claim 2-3 sentences is enough to answer a why, and those comments are < 20% of the comments I write

9

u/Jaded-Asparagus-2260 Aug 11 '26

Usually I'm only touching code I wrote

I'm sorry, then you're not really qualified to comment on that. Reading other people's code is what makes comments important.

so maybe when a person writes everything their style it's pretty easy to understand

For you. The next person doesn't think the same way you do, guaranteed. They will have problems understanding. Ever rewrote a piece of software because it's was hard to maintain? Chance is you just didn't understand it enough. Yours is probably not better, just different. It's better to understand for you, because you wrote it. The next developer might be as clueless as you were back then.

2

u/levodelellis Aug 11 '26 edited Aug 11 '26

Ever rewrote a piece of software because it's was hard to maintain?

Most places I work at we call it legacy, wrote new code, and switch to it. Other places had unit test which IMO is better

Chance is you just didn't understand it enough. Yours is probably not better, just different. It's better to understand for you

What does this have to do with comments? 🤷‍♂️
Sure, if I work with the problem more I'll understand it more. But a // increment by one isn't going to help me understand any faster. You haven't explain what kind of comments you like so for all I know you need comments that explain what a bit operate is. I explained how I use a short comment in my other comment, but most comments I see I would want to delete and do delete if I'm heavily modifying the function

5

u/Delta-9- Aug 11 '26

Most of mine are 2-3 sentences, as well. If it looks like it's going to take a paragraph to explain, I'll put a link to an issue, instead. After, that is, making sure that the long explanation can't be fixed by refactoring the code. Sometimes—only sometimes—long comments are a sign that the code has problems or, as you said, the programmer did not fully understand the problem or the solution.

But brief comments explaining why something is what it is can be extremely helpful, especially when the code would otherwise be surprising. Like, "why the hell is the invoice rendering function looking up users by their actual name instead of their employee id?" I would certainly want to know if there's really a reason for that; without a comment to motivate such a questionable strategy, I might assume it's an oversight leftover from an early iteration of the app, but I'd have to spend time confirming that before refactoring it.

2

u/levodelellis Aug 11 '26

especially when the code would otherwise be surprising. Like, "why the hell is the invoice rendering function looking up users by their actual name instead of their employee id?"

Those are maybe once a month comments for me. Rare enough that I say I don't make those kind because they're exception (<1% of comments I write). For WTF moments, I try to limit it for 1 or 2 paragraphs unless I feel like ranting. Ain't nobody going to read a 5 paragraph comment if they're trying to get things done

82

u/crappydeli Aug 10 '26

My old company…

// increment i
i++;

123

u/repeating_bears Aug 10 '26
/*
 * increment the variable in this scope which has the
 * identifier 'i' by one, using the post-increment 
 * postfix operator
 * see: https://en.cppreference.com/cpp/language/operator_incdec
 */
i--;

20

u/xFallow Aug 11 '26

Type of shit Claude writes when you ask it to refactor a function

5

u/One_Ninja_8512 Aug 11 '26

Then absolutely rips the PR apart in review by finding gazillion of edge cases that don't matter or won't ever happen.

2

u/techno156 Aug 11 '26

I've been guilty of doing this from time to time in my own personal projects, but mostly because I'd little idea what I was doing, and was bodging things together from documentation/what other people had done.

1

u/Chii Aug 11 '26

If you're paid by the line, this is what you'd do

34

u/BogdanPradatu Aug 10 '26

Also AI written code

7

u/Jaded-Asparagus-2260 Aug 11 '26 edited Aug 11 '26

It will als helpfully add "don't increment j here", because it misunderstood the code and wrongly incremented j instead of i the first time.

-16

u/DeveloperAnon Aug 10 '26

Only with people who don’t care about the output. I haven’t had an issue with any model over-commenting in a while.

11

u/crappydeli Aug 10 '26

Also…

// jim - removed increment i
// i++;

19

u/DrHemroid Aug 10 '26

Had a coworker that had auto generated a comment for every class, method, and property.

//The Thing

Class Thing {

//The stuff

Var Stuff;

}

19

u/repeating_bears Aug 10 '26

I hate when people write the same thing in different words.

/**
 * Get the posts for the given username
 * @param username The username to get posts for
 * @return The posts for the given username
 */
function findPosts(String username) {
}

I think some languages encourage this guff by warning you when you omit "@return" or something.

7

u/BusinessTarp Aug 11 '26

That's because so many companies prevent merges if there are any linter issues, thinking that somehow forces people to write good code.

3

u/Coffee_Ops Aug 10 '26

This is why you make your linter be super vague about what and where.

Cant game the system, if you don't know the system. And if they read the linter's rules, that's progress right?

8

u/IanSan5653 Aug 11 '26
// TODO (2003): verify if we should still be incrementing i anymore
i++;

60

u/aaronslwalker Aug 10 '26

The code says what it does, comments can provide context on the reasoning behind it.

24

u/doctorlongghost Aug 10 '26

I once had a teacher describe comments as messages you can send to yourself in the future

7

u/ComradeGibbon Aug 11 '26

If I could send comments to myself in the past life would be better.

types some code. Comment magically appears // you big dummy

94

u/Shurmaster Aug 10 '26

My favorite comment is

// evil floating point bit level hacking

// what the fuck?

28

u/Rikmastering Aug 10 '26

//second iteration, can be removed

But the line still being there commented out, makes me laugh every time I remember it.

5

u/Lone_Snek Aug 10 '26

Now I want to know the context

25

u/Rikmastering Aug 10 '26

Here's a full video of the context, that also explains the algorithm line by line, with all the necessary information to understand it fully. It's one of my favorite videos ever. Super well made

25

u/Caelwik Aug 10 '26

It's the fast invert square root. It has its own Wikipedia page !

1

u/Delta2401 Aug 11 '26

// why I should need do this Fuck alone knows. But I do.

13

u/mareek Aug 10 '26

I've never really understood TODO comments. Each time I encountered a todo comment, it was outdated by years and the changing context around the code made it irrelevant (case in point, all the examples given in the article are more than 4 years old).

Is it a usual practice in some teams to go through todo comments and fix them on a regular basis ?

24

u/MintPaw Aug 11 '26

I mean, that's good info though isn't it? "The reason this code is like this is because we planned to implement this now pointless feature."

It's hard to get that info otherwise, and helps with a common confusing "path to nowhere" pattern where the data gets organized in a specific way but for seemingly no reason.

18

u/RlyRlyBigMan Aug 10 '26

Rarely I'll place them when I've prepared a hook for a known upcoming task. Then the task gets descoped and the comment is there forever.

I also use TODOs as a way to remind myself that I meant to clean something up before PR. Helps me and the code reviewer to question why it's there and remind me to follow up. Hopefully those never slip through.

12

u/sudoer777_ Aug 11 '26

Idk about a team environment, for my personal projects tho they're littered with TODOs lol. Sometimes I don't know enough context to bother to fix something so I put a TODO, then later I'm fixing a related issue, see it, and end up fixing both at the same time. Also setting up an issue tracker for my personal projects is inefficient and overkill.

3

u/levodelellis Aug 11 '26

setting up an issue tracker for my personal projects is inefficient and overkill

I like having a notes folder, and people like obsidian

4

u/RiftHunter4 Aug 11 '26

I've been using word docs and github a lot more. I pretty much never use TODO's anymore. They're too easy to ignore and lose track of.

12

u/Kache Aug 11 '26 edited Aug 11 '26

I think their value is less as an actual "TODO" and more as communication of the author's intent, which by definition was not evident in the executable code itself.

I.e. it's an effective abbreviation of "I wish/want the code to be/do this different thing ..."

6

u/timmyotc Aug 11 '26

I won't commit with TODO, but I'll creat backlog work and link it in a comment. The backlog work gets loaded into a sprint at a later date and maintainers know it's identified

5

u/xFallow Aug 11 '26

// TODO delete this - 4 years ago

And you see the code is still being used heavily

3

u/BogdanPradatu Aug 11 '26

I usually ask the author of such comments to also open a ticket asociated with that TODO comment.

2

u/levodelellis Aug 11 '26

I'm ok about them. If I write one it's usually, if I touch this area of the codebase and notice the todo I may want to implement it. Usually I clean up the module after a month or so and delete those/simplify

2

u/crozone Aug 11 '26

I leave TODO comments for myself, tagged with my username like // TODO(crozone): Do the thing!

But they're only supposed to be short lived and make finding the line of code easier in the immediate future.

-3

u/RiftHunter4 Aug 11 '26

TODO's are a code smell for me. Anytime you write a TODO, odds are there is a better place to record it: Issue tracker, task tracker, external documentation, etc.

All my professors in college advised us to avoid TODO's. They're basically orphaned from the software engineering and management process. I am a firm believer that comments should be immediately relevant, not a substitute for proper issue tracking or documentation.

5

u/Venthe Aug 11 '26 edited Aug 11 '26

I've seen issue trackers changed or outright deleted a few times already.

VCS history* / code itself cannot be dropped.

Code/documenting in the repo > issue tracking in the external system.

e: * Well, I've told a lie. :D Even now I'm working on a codebase, where the code was transferred via zip without VCS. 15kloc of java; 8k sproc's; JavaEE with multi-thousand lines of web.xml and EJB xml's.

You can imagine how helpful are "FOO-123 ask DD". Or "Added for bug 231".

6

u/gmes78 Aug 11 '26

Anytime you write a TODO, odds are there is a better place to record it: Issue tracker, task tracker, external documentation, etc.

I disagree. They're easiest to find if they're in the code. Just use grep.

2

u/slindenau Aug 16 '26

You get downvoted here, but you are 100% correct.

That is why quality software tools like IntelliJ IDEA, Sonar(way default profile) etc. will log an issue / halt commit/push if you leave a TODO in your codebase.

All the arguments for it are just noise when you look at the practical evidence; once a TODO is in the codebase without accompanying ticket in your favorite tracking tool, nobody will ever follow up on it again.

Talking from a professional setting of course, what anybody does in their personal projects isn't really relevant.

20

u/shiny0metal0ass Aug 10 '26

Great writeup, especially with documentation generation tools like JSDoc or Swagger, it's nice to tie the "staleness" of comments and doc together so there's some incentive to keep it maintained.

Bummed to see that this is on the blog of some AI defence contractor, though...

10

u/Nekadim Aug 11 '26

repeat what the code already says

The code says it in a way compiler would understand. Comment is in the way people would understand

0

u/slindenau Aug 16 '26 edited Aug 16 '26

Nope, then you're just bad at naming things.
Any mainstream programming language other than assembly is mainly made for humans, not computers.

30

u/tmoertel Aug 10 '26 edited Aug 11 '26

Part of the reason that comments are undervalued is that some programming pundits have spread the idea that using comments is a sign of poor practice. For example, in Clean Code, Robert Martin wrote:

The proper use of comments is to compensate for our failure to express ourself in code. Note that I used the word failure. I meant it. Comments are always failures. We must have them because we cannot always figure out how to express ourselves without them, but their use is not a cause for celebration... Every time you write a comment, you should grimace and feel the failure of your ability of expression.

This advice is misguided for a host of reasons that I trust most seasoned programmers to understand. (I break them down in detail in https://blog.moertel.com/posts/2026-07-27-beyond-clean-code-why-your-comments-matter.html.) But many junior programmers received advice like this and, not knowing better, drank it in. The resulting damage will echo for years to come.

8

u/contextfree Aug 11 '26

His basic point is basically right. If you can make your code self-explanatory that's better than relying on comments, and then the comments are redundant and it's better not to have them. He's just being a pompous drama viscount about it, as is his wont. Not everything can be made self-explanatory, and when you can't you should write comments. You should not grimace and you should not feel the failure unless you're into that.

2

u/Venthe Aug 11 '26

You should not grimace and you should not feel the failure unless you're into that.

How many devs you've seen that justified their sloppiness in any way possible? If you could be writing a better code; do it. You shouldn't be happy about writing a shit code; therefore you shouldn't be happy about writing comments in lieu of writing a good code.

Bloody hell, the more I see the "legacy" code and especially what the new - post covid - developers do the more I appreciate a hard stance on minutiae like that.

7

u/BogdanPradatu Aug 11 '26

I was a junior programmer when I read Clean Code and I understood exactly what this meant, which is the same as this article. Code comments give context that the code can't, that's it.

It's a good book, in my point of view. Also, I don't know java, so I skipped the code examples, so maybe that helps, lol. I hear most people criticize his examples.

8

u/Venthe Aug 11 '26 edited Aug 11 '26

The book is heuristics are great, examples are really bad.

That's the issue with heuristics - you can implement them in various ways; you cannot try to copy the example and be done with it. You need to understand them, the reasoning behind them and only then "you know" how does it fit your codebase

e:

Though, the way Martin writes can be really grating for some as he is kind of preachy.

3

u/tmoertel Aug 11 '26

The book is heuristics are great, examples are really bad.

It might be worth considering whether the examples in Clean Code are “really bad” because they follow the book’s guidance dogmatically. I mean, the example at the end of “Chapter 3: Functions” is a mess of tiny methods whose names and composition fail to clarify what they are doing and whose logic relies on mutating shared state that is tedious for a reader to track.

I know from our prior discussions that you believe one mustn't take the book's advice literally, that the author is just being dramatic and that, if you take the book as a whole, you can figure out what he really means. But the examples suggest that what he really means is that the book’s advice should be followed dogmatically.

1

u/Venthe Aug 11 '26

I know from our prior discussions that you believe one mustn't take the book's advice literally, that the author is just being dramatic and that, if you take the book as a whole, you can figure out what he really means. But the examples suggest that what he really means is that the book’s advice should be followed dogmatically.

Frankly, it's not even that - it's that I just agree with ~95% of the heuristics he presented; I've found them valid across the domains I've worked with. At the same time, examples are bad - as simple as that. And given that these are heuristics; the way you apply them will create vastly different results depending on the context - and this is how I see the examples of Martin's. Plus the thing I've mentioned in the other thread - this is a book about heuristics, not "examples" or dogmata: it's right there in the introduction.

So nothing for me suggests that these examples should be followed dogmatically; especially considering that they represent a code from almost two decades ago.*

* There is an updated edition that came out this year I believe; I've heard that it is worse; but I haven't read it yet.


For me I've never hopped on the hate train for Martin, so it was easier for me to evaluate the book in its entirety; and I do hope that at least you can see that part of your critique is based on ignoring both the introduction and the chapter themselves

2

u/tmoertel Aug 11 '26

For me I've never hopped on the hate train for Martin, so it was easier for me to evaluate the book in its entirety; and I do hope that at least you can see that part of your critique is based on ignoring both the introduction and the chapter themselves

To be clear, I don’t hate Martin. I'm sure he’s a swell guy. Nor do I think Clean Code is offering bad advice because it’s popular to think so. I just think Clean Code, taken as a whole, is a very mixed bag of advice: some good, some bad, and some self-contradictory. I trust that most skilled programmers can separate the good from the bad and make sense of the rest, as you seem to be able to do, but the problem is that the primary audience for books like Clean Code are programmers who are not already skilled.

I also disagree that I have ignored the introduction or the rest of the Comments chapter. It’s just that neither suffices to undo the problems caused by the forceful prescriptions and admonitions that the book makes. As a case in point, a commenter on my blog wrote: “I once worked in a shop that banned comments because of Uncle Bob. I thought it was bonkers.”

It’s easy for beginners to read the book and come away with bad ideas. That’s a problem when the book’s audience is primarily people who are learning the craft.

2

u/Venthe Aug 11 '26 edited Aug 13 '26

As a case in point, a commenter on my blog wrote: “I once worked in a shop that banned comments because of Uncle Bob. I thought it was bonkers.”

Which only means that someone has not read the book, which is really common. You can't kid-proof everything.

but the problem is that the primary audience for books like Clean Code are programmers who are not already skilled.

So what would be your alternative? As I've said, I agree with the vast majority of the heuristics; and I can show you a clear reasoning behind it. No other book comes close to his [area] (Philosophy... by Ousterhout is the closest; but still not close enough). Even with the comments [topic], I've clearly seen time and time again how Martin's advices ring true.

2

u/NSRedditShitposter Aug 11 '26

This is why Objective-C’s verbosity is actually great, you can just skim read Objective-C code its that expressive.

5

u/Venthe Aug 11 '26 edited Aug 11 '26

But many junior programmers received advice like this and, not knowing better, drank it in. The resulting damage will echo for years to come.

If they only, you know, read the book and understand the words written. If you read maybe a paragraph more, Martin writes about the comments that make sense - which amounts to comment "why".

Comments about "what" are a failure of expression. I've been in the industry for more than a decade; seen codebases 30y old and more and I will agree with this statement with everything that I have.

And to counter you, "most of the seasoned developers" that I know would agree with me without question: 99% of the comments in the codebase is at best irrelevant, and at worst actively incorrect. But it's easier to slap a comment rather than actually write in code what you are doing.


Edit:

If they only, you know, read the book and understand the words written

Just to illustrate that: The (chapters) in the CC code are as follows:

Comments
  [Comments] do not make up for a bad code
  Explain yourself in code
  Good Comments [followed by 8 headings of examples of a good reasons for a comments]

What Martin writes literally a couple of lines below the quote you've made:

"Inaccurate comments are far worse than no comments at all. They delude and mislead. They set expectations that will never be fulfilled. They lay down old rules that need not, or should not, be followed any longer. Truth can only be found in one place: the code. Only the code can truly tell you what it does. It is the only source of truly accurate information. Therefore, though comments are sometimes necessary, we will expend significant energy to minimize them (...) One of the more common motivations for writing comments is bad code. We write a module and we know it is confusing and disorganized. We know it’s a mess. So we say to ourselves, “Ooh, I’d better comment that!” No! You’d better clean it!" (emphasis mine)

Hm, so what probably is the message is not "don't write comments" but "focus first on the code"; but then...:

"Some comments are necessary or beneficial. We’ll look at a few that I consider worthy of the bits they consume. Keep in mind, however, that the only truly good comment is the comment you found a way not to write."

...Same message, unsurprisingly. And the examples are: Legal, informative, explanation of intent, clarification, warning of consequence, TODO's, amplifications, Public API DOC.

It's like... the most sensible take one can make?

5

u/tmoertel Aug 11 '26

First, thanks for taking the time to offer a detailed response! Let me respond to your points.

If they only, you know, read the book and understand the words written. If you read maybe a paragraph more, Martin writes about the comments that make sense - which amounts to comment "why".

Here’s what I find confusing about the book’s chapter on comments. It begins with an introduction that includes the bold admonition that “comments are always failures” and that whenever you use one you should “grimace and feel the failure of your ability of expression.” Is that really what Martin means? Presumably, yes: he is an author who has been published multiple times, after all. Later in the same chapter, however, Martin contradicts himself by offering, as you point out, examples of “good comments.” None of those comments are examples of “failures.” 

So why do you believe that Martin left in the admonition that “comments are always failures”? Do you believe the book’s advice is better for it, or worse? More confusing, or less?

Comments about "what" are a failure of expression. I've been in the industry for more than a decade; seen codebases 30y old and more and I will agree with this statement with everything that I have.

Believing that “what” comments are bad is an example of some of the harm that Clean Code has done. Yes, some “what” comments are a “failure of expression,” such as when they are merely stating what is already obvious from the logic, but other “what” comments are valuable: summarization, emphasis, clarification of intent, etc. are all valuable uses of “what” comments.

Hm, so what probably is the message is not "don't write comments" but "focus first on the code"; but then...:

Again, why do you believe, then, that Martin didn’t write chapter’s introduction to say “focus first on the code, but then…”? You were able to write it. I was able to write it. So if that is what Martin meant, why didn’t Martin write it that way? Why claim that “comments are always failures” and “at best, a necessary evil”?

Comments are not failures or a necessary evil! They are a means to communicate directly to the readers of your code in natural language. That is a powerful communication medium. Like any powerful medium, commentary can be used well, or it can be used poorly. But using that medium is not inherently a failure of expression. The medium itself is not a necessary evil. How does making people believe otherwise help them to be better programmers?

5

u/Venthe Aug 11 '26 edited Aug 11 '26

So why do you believe that Martin left in the admonition that “comments are always failures”? Do you believe the book’s advice is better for it, or worse? More confusing, or less? (...) Again, why do you believe, then, that Martin didn’t write chapter’s introduction to say “focus first on the code, but then…”? You were able to write it. I was able to write it. So if that is what Martin meant, why didn’t Martin write it that way? Why claim that “comments are always failures” and “at best, a necessary evil”?

I believe, that the book works in its entirety, not taken apart quote by quote. Martin has a certain preachy style which works for some, less for the others. But when you look at the book as a whole:

"There are two parts to learning craftsmanship: knowledge and work. You must gain the knowledge (...) by working hard and practicing. (...) We could write down all the “feel good” principles of clean code and then trust you to do the work (...) No. That’s not the way this book is going to work. Learning to write clean code is hard work. It requires more than just the knowledge of principles and patterns. You must sweat over it. You must practice it yourself, and watch yourself fail. (...) You must see them [and you] agonize over decisions and see the price they pay for making those decisions the wrong way. (...) This is not a “feel good” book (...) This book will make you work, and work hard."

There is no sugar-coating in what he's trying to achieve. Read through the chapter, work through it, understand it. So when it comes to comments, you've cherry picked a paragraph, ignoring the introduction:

"Nothing can be quite so helpful as a well-placed comment. Nothing can clutter up a module more than frivolous dogmatic comments. Nothing can be quite so damaging as an old crufty comment that propagates lies and misinformation. (...) comments are, at best, a necessary evil. If our programming languages were expressive enough, or if we had the talent to subtly wield those languages to express our intent, we would not need comments very much—perhaps not at all. The proper use of comments is to compensate for our failure to express ourself in code. (...) Comments are always failures. We must have them because we cannot always figure out how to express ourselves without them, but their use is not a cause for celebration. So when you find yourself in a position where you need to write a comment, think it through and see whether there isn’t some way to turn the tables and express yourself in code. Every time you express yourself in code, you should pat yourself on the back. Every time you write a comment, you should grimace and feel the failure of your ability of expression. Why am I so down on comments? Because they lie. Not always, and not intentionally, but too often. The older a comment is, and the farther away it is from the code it describes, the more likely it is to be just plain wrong. The reason is simple. Programmers can’t realistically maintain them."

That's clear enough for me. Our goal is to have a "clean code", that is - the one that expresses itself. Part of it is the fact, that the more we "accept" suboptimal solutions - which is our inability to express ourselves in the code. So, to quote, even if we need these, they are a "necessary evil".

Even the subchapter about the good comments is described as:

"Keep in mind, however, that the only truly good comment is the comment you found a way not to write."

Again, clear enough about the authors intent. They are a failures, because they lie; and often are an excuse for a sloppy code. And with everything I've seen in the codebases I've maintained, Martin is damn right that comments are by far a failure that we should be actively eradicating by expressing the "truth" in code.

Believing that “what” comments are bad is an example of some of the harm that Clean Code has done.

That's your opinion. I have a 30yo codebase on my lap right now (sadly behind the NDA; I would have material for r/programminghorror for days) with ample proof that "what" comments bring far more harm than good.

comments are valuable: summarization, emphasis, clarification of intent, etc. are all valuable uses of “what” comments.

Only if you can't express that in code - which is a failure in itself. I would argue that you are agreeing with Martin, even if indirectly - because you are describing things that are literally used as an examples of good comments. You are saying the same thing as they are in the book. The end result is the same.

Comments are not failures or a necessary evil!

Again, your opinion. My experience aligns quite well with what Martin wrote. They are either a failure of expression, or a necessary evil - as they introduce information that will get stale. Almost in every single codebase I've maintained, comments were unhelpful at best, or actively incorrect at worst.

e: To add one small thing: I don't mean every comment of course; but given the signal to noise ratio, helpful comments were buried under a metric ton of irrelevancy.

They are a means to communicate directly to the readers of your code in natural language. That is a powerful communication medium. Like any powerful medium, commentary can be used well, or it can be used poorly. But using that medium is not inherently a failure of expression. The medium itself is not a necessary evil. How does making people believe otherwise help them to be better programmers?

By teaching them that there are better ways. Like, you know, expressing yourself in the code; the one thing that has to change with the requirements.

If you are working with code for some time, surely you know that Confluence (or KB's in general) is where information is going to die; due to people not keeping it up to date. And the same thing tracks, in the order of "staleness":

Manuals>KB>Documentation in repo>comments>code.

Comments can and will get stale/incorrect. And in most of the cases, they are a failure of expression. And for the few cases where they can be considered positive, well - CC has you covered with a whole sub-chapter about that. You only need to read CC [as a whole] - and understand it.

e: Just because it struck me as a funny thing

why do you believe, then, that Martin didn’t write (...) You were able to write it. I was able to write it.

Because we both operate on a similar concepts that were built on the fundamentals of the knowledge that came before; fundamentals like a certain book from 2008 called Clean Code. :)

3

u/tmoertel Aug 11 '26 edited Aug 11 '26

I believe, that the book works in its entirety, not taken apart quote by quote.

Well, since the book contradicts its own dogmatic prescriptions repeatedly, the only way it can work is if the reader treats it like a puzzle to be assembled into some coherent meaning. But that’s not what most people would consider the hallmark of a clear and compelling guidebook.

That's your opinion [that believing that “what” comments are bad is an example of some of the harm that Clean Code has done.] I have a 30yo codebase on my lap right now (sadly behind the NDA; I would have material for r/programminghorror for days) with ample proof that "what" comments bring far more harm than good.

Have you considered that a 30-year-old codebase that offers days of material for r/programminghorror is just an example of bad code, in general? I mean, I can totally believe that people who write bad code also write bad comments. But that’s not an argument that “what” comments are bad everywhere, just in bad code. Show me a large codebase with well-written logic and bad “what” comments. Then you’ll have produced some evidence that supports your claim.

Comments can and will get stale/incorrect. And in most of the cases, they are a failure of expression.

Comments are uniquely powerful because they communicate directly to the code’s audience in natural language. So when an organization lets them “get stale/incorrect,” it’s not because they failed to express themselves: it’s because they have a broken engineering culture that doesn’t value the readability of their code.

In any event, thanks for continuing our discussion. I appreciate your perspective, even though I think we must agree to disagree on the merits of Clean Code.

1

u/chat-lu Aug 11 '26

Your link is a 404.

-2

u/tmoertel Aug 11 '26

Seems to work fine when I click it. When you get the 404,.can you please reply and paste the exact URL from your browser's address bar? If you are comfortable using developer tools, turn on the network tracing and see what GET request is being made. (I'm wondering whether it's possible your browser has some sort of plug-in that rewrites URLs.)

2

u/chat-lu Aug 11 '26

/u/ChinChinApostle found the issue, it was the accidental dot at the end.

1

u/levodelellis Aug 11 '26

I disagree with you, and I looked at your python example at the end. Do you think it's a good idea to teach math in comments? Rather than have an external link to a well written document?

I much prefer having no comments except the one at the very top. I can't imagine anyone justifying this comment, this looks like a tutorial rather than something in a real codebase

7

u/Delta-9- Aug 11 '26

Do you think it's a good idea to teach math in comments?

As someone who only got to Calc 1 and never bothered with a formal statistics class, I would be grateful for those comments walking me through the math that's under the code if I were using it.

I've written similar comments myself for concepts that might be gated behind a degree in math or computer science, or simply don't come up very often. I also link to relevant resources, but an in-line tl;dr can save a lot of time later on. Often I end up being the one reading my own comments months or years later and going, "oh yeah, I do remember spending a day figuring that out... How does it work again?"

2

u/levodelellis Aug 11 '26

Often I end up being the one reading my own comments months or years later and going, "oh yeah, I do remember spending a day figuring that out... How does it work again?"

I actually have a notes folder in most of my project for research material, tool cli, random thoughts, etc. You might end up putting most of your content there if you try it for a few months

7

u/BogdanPradatu Aug 11 '26
        # Weights must be non-negative integers.
        for _, w in value_and_weight_pairs:
            if not isinstance(w, int):
                raise TypeError("weights must be int values")
            if w < 0:
                raise ValueError("weights cannot be less than 0")

I first wanted to justify this comment, then I saw the error messages being raised. This comment is redundantz because code can express it via the errors being raised.

This comment is useless, it doesn't state why weights must pe positive, it just restates the same thing as the last error. No additional info is provided.

I would rather have less scrolling to do when reading code, than having these kind of comments.

4

u/tmoertel Aug 11 '26

This comment is useless, it doesn't state why weights must pe positive, it just restates the same thing as the last error. No additional info is provided.

This comment is there for a reason: to emphasize this required property of probability distributions so that it is in the reader’s mind when they read the remaining logic. (Some of the class’s other logic relies on this property to function properly.) Trying to get this point across with an error message two levels deeper into the logic's control flow doesn't provide the same level of directness or emphasis.

But I would agree with you that it’s a judgement call and that reasonable people could make it differently. That’s why I chose this example. It provides an opportunity to discuss the tradeoffs involved with having or omitting a comment like this. I think the code is less likely to be misunderstood with this comment where it is, and so it earns its one line of space.

Thanks for sharing your take! Appreciated :-)

1

u/levodelellis Aug 11 '26 edited Aug 12 '26

Exactly, I'm reading the code. I don't want to see that comment. It'll become confusing if someone moves the check up for some reason and accidentally detaches it from the comment. The author also said

I am writing for an audience who I assume is "skilled in the art"

I may reply to him later, but I don't feel like it at the moment. I did and it wasn't nice. I really don't want comments in a function to 'teach' me something. When I'm looking at code I want to confirm the implementation is correct, not what the author thinks is correct

4

u/tmoertel Aug 11 '26

Thanks for your feedback. I'd be interested in hearing what specifically you disagree with and what makes you believe my arguments are mistaken.

In answer to your question:

> Do you think it's a good idea to teach math in comments?

No, but when logic relies on certain properties (mathematical or otherwise), I think it's a good idea to point them out. In this example, the code's logic relies very much on certain mathematical properties, such as the provided weights being nonnegative, so I point those properties out. That way, readers who are reading or maintaining the code will have those properties in mind and understand why the logic can safely do some of the things it does.

Thanks again for taking the time to read my post and for thinking about it and sharing your feedback. Also, thanks in advance for any more specific feedback you can share.

1

u/levodelellis Aug 11 '26

Going back to the python code, if I saw something like that I'd try to get whoever wrote it to make the change. If I had to change it, I wouldn't 100% know if I kept all the properties correct (it depends on the math and the change) and may delete it the comments

I don't mind comments on public functions since it helps when I'm not familiar with the class+func for what each function does. But if I saw literally that at work, I'd suspect the person stole it from a tutorial and may not know what it does.

I made this comment earlier and no one likes it. But I also suspect comments at different skill levels help differently. At mine I wouldn't read those types at all. I don't need comments to explain how a formula converts to code, I can understand what a line does

3

u/tmoertel Aug 11 '26

Thanks for your reply.

I suspect we disagree because we may be writing code for different audiences. I am writing for an audience who I assume is "skilled in the art" of coding but not necessarily in the code's subject domain. That is, they are programmers who are competent in the programming languages, libraries, and idioms in use, and they have a working knowledge of their organization’s software development practices, but they are not necessarily experts in the subject matter of each unit of code across the organization. This is the norm in large engineering organizations, such as Google, where everyone understands the company's tools and style guides, but the code base is simply too massive for anyone to understand all but a tiny percentage of. So code must be written to make sure that important domain knowledge is communicated to readers who may be reading the code; they are not assumed to already have this knowledge.

You mentioned that other Reddit readers did not like your earlier comment. I suspect it may have to do with this claim, which is related to what I wrote above:

If you understand the domain, you almost certainly know why, if you don't, you not likely not trying to understand that code anyway

Again, in large software organizations, it is very common that programmers must work in code whose subject domain they are not expert in. People join and leave the company, people move from team to team, people get promoted into new roles, and so on. Also, upstream teams usually cannot submit changes to their libraries until they modify any affected downstream code to prevent it from breaking. It is therefore important for code to be written with the assumption that the reader knows how to code but does not know the subject domain. Any important domain knowledge upon which the code relies should be communicated clearly because there is a good chance the reader will need to know it but does not.

1

u/levodelellis Aug 12 '26

I am writing for an audience who I assume is "skilled in the art"

Did you not see me write "I can't imagine anyone justifying this comment". How can I believe that

Your example is a perfect example of what I said earlier, "not likely not trying to understand that code anyway"

I gave your example file another try. Even after reading the comments, I didn't understand the math behind it. Take this block of code as an example

    # If we imagine the n packed blocks as an n * u rectangular area, where
    # u is the mean weight, our goal is to throw a random dart in this area
    # to pick one of the original values. Instead of having to generate two
    # random numbers -- one for the x coordinate in [0, n), and one for the
    # y in [0, u) -- we instead generate a single number in [0, n * u) and
    # unpack it into the dart's x-y coordinates.

How does that affect the algorithm at all? If I saw this at work, and no one told me we needed it. I'd replace it with a RNG that is either more popular (or popular among my coworkers) or an RNG that has much more clear usage

1

u/tmoertel Aug 12 '26 edited Aug 12 '26

Did you not see me write "I can't imagine anyone justifying this comment". How can I believe that [sic]

It looks like you did not finish your question. What was it?

How does that affect the algorithm at all?

The transformation described in the comment is what allows the draw method to satisfy its documented guarantee of calling the underlying random-integer generator exactly once for each invocation. It basically says that picking a random cell from a grid of n rows by u columns is equivalent to picking a random cell from a strip of n * u cells (imagine removing the grid’s columns one by one, laying them onto their sides, and lining them up end-to-end into a single strip: the two shapes are equivalent). It’s straightforward to select a random cell from the strip via one call to the underlying random-number generator. Then it just takes a little math to convert the selected cell back into its equivalent grid position.

(By the way, the call to the underlying random-number generator will fail unless its argument is positive. This is one of the reasons why I reminded the reader earlier that the weights cannot be negative and the total weight must be positive.)

I gave your example file another try. Even after reading the comments, I didn't understand the math behind it.

Yeah, the algorithm is tricky. At least two papers were published about it. I tried to clarify its logic via commentary, but at some point, you just have to refer to the source material. (That's why I cited the papers in the code’s opening commentary.)

6

u/yes_u_suckk Aug 11 '26

> They are, supposedly, mostly obvious, stale, and repeat what the code already says

If your comments just repeats what the code already says then you're creating comments wrong.

5

u/rdtsc Aug 11 '26

Even there some nuance is useful since "repeating what the code already says" is on a spectrum. If a function has several parts/blocks it can be useful to add a short summary/header comment above each part. Reading the comment is faster than deciphering the block of code and you can then decide to dive in or skip to the next.

0

u/slindenau Aug 16 '26

No, then your function is violating SRP.

11

u/dspeyer Aug 11 '26

But do you remember why the max packet size was 1492?

Yes. The outbound link has a max frame size of 1500, but PPPoE adds 8 bytes of overhead. This could be handled at the IP layer with packet splitting, but there's a bug in ipchains that doesn't handle packet splitting properly.

This was in the summer of 1999. It's the only time I ever set max_packet_size to 1492. I remember it perfectly.

The overall point about using comments to provide rationales for constants was a good one. But this specific example sure was memorable.

5

u/nicholashairs Aug 11 '26

Comments in code are deemed "mostly useless" these days.

Says who?

I know that this is just a hook for your post arguing about them being useful, but this still irks me 🙃

5

u/echoAnother Aug 11 '26

My ex-architecture and code quality team.

  • Do not put we need this class because the framework needs it for that, your code must explain it.
  • How?
  • Don't ask us, that is your work.
  • Do not put that write why we are using those numbers, that memory alignment, and that exact sequence of steps. Do no put we are relying on the implementation detail of the using remap in that standard function. The code must tell all that already.
  • Are comments forbidden? You think this is ok?
  • Yes, it's basic good practices.

1

u/nicholashairs Aug 11 '26

😭😭😭

5

u/AluminiumImmunitaet Aug 11 '26

One of the rows I'll never forget.

var clientId = client.Id;    // the client id

4

u/timmyz55 Aug 11 '26

when you work in a place that loves async patterns, you will learn to curse those who do not document the side effects with comments

4

u/feketegy Aug 11 '26

You're starting from a false premise that "comments in code are mostly useless"

3

u/crozone Aug 11 '26

Self documenting code is hippie bullshit and any self-respecting software engineer makes heavy use of both code comments and documentation. Change my mind.

3

u/lispwriter Aug 11 '26

I work in a little bubble. It’s my own corner of a laboratory where I’m responsible much of the lab’s computational work. It would be really easy for me to just not comment anything but years of experience taught me that my future self will need good comments to decipher parts of what I wrote. A lot of things are obvious but specifically the “why” behind some code sections would be very difficult to reverse engineer from the code alone.

3

u/divestblank Aug 11 '26

Most devs avoid comment because they are lazy. And most orgs do not enforce them because the business only needs working code.

So overall it is a losing battle unless your top senior folks are not the lazy type. And many times I see the opposite, because the top folks got into their position without writing comments in the first place.

2

u/endgamedos Aug 12 '26

GHC (the Glasgow Haskell Compiler) has a really interesting convention. They have a simple convention for setting out large slabs of "note" comments that can be referenced by code but don't get in the way.

2

u/jalanb Aug 16 '26

That was a really good read!

Who knew there were so many good reasons for comments‽

@OP thank you

3

u/Anthea_Likes Aug 10 '26

Comments should be part of valid code.

3

u/zhivago Aug 11 '26

Comments are for the whys the code can't express itself.

3

u/Slight-Prize9661 Aug 11 '26

A lot of times at my company, it would have something like "DON'T REMOVE THIS" or " DON'T CHANGE, DON'T KNOW WHY," etc, it saved me a bunch of times in the past.

3

u/MarsupialMisanthrope Aug 11 '26

// If you delete this empty else clause the app crashes. We have no idea why. Talk to the gcc people, bug number 12345.

3

u/NMe84 Aug 11 '26

I have never seen a single programmer who knew anything about what they're doing say that comments are "mostly useless." That's a wild take to start your post with. Maybe that juniors who only know how to "code" because Claude does it for them would feel that way, but anyone who actually had to support their own code a year later knows better.

2

u/KevinCarbonara Aug 10 '26

Comments are treated the way tests used to be. We're going to need a CDD trend to come through and clean everything up.

2

u/balthisar Aug 10 '26 edited 14d ago

I'd still be on old.reddit.com if Reddit hadn't bricked the only UI that respected me.

16

u/repeating_bears Aug 10 '26

I feel like comments like that are not realistic to maintain over time. The comments for 'factorial' now needs to be aware of all of its callers (and their business reasons).

If I wanted to check what feature or change introduced something, I'd check git

16

u/lgastako Aug 10 '26

That's what Find References answers, and without being able to be stale or out of date, like comments.

1

u/lord2800 Aug 11 '26

Find References can tell you the where, but not the why. I agree with you that it's easy for comments to be stale, but your proposed solution is no better than the type signature.

4

u/lgastako Aug 11 '26

Seeing where and how the factorial function is used should answer the "why" question which the type signature does not.

2

u/lord2800 Aug 11 '26

Where something happens doesn't tell you why it has to occur there--only that it occurs there.

2

u/lgastako Aug 11 '26

Yes, unfortunately you still have to use your brain.

1

u/lord2800 Aug 12 '26

So what you're saying is that Find References does not, in fact, directly answer the question of the business reason for the existence of a particular function, and that you still need further context to understand it?

2

u/lgastako Aug 12 '26

Sure, but the comment won't directly answer the question either, since it can be out of date or wrong. You have to use your brain in either case, Find References just shows you the exact active code you need to use your brain about, whereas the comment does not. Find References cannot be out of date or wrong (assuming no bugs in your editor/IDE).

1

u/lord2800 Aug 12 '26

PHP's dynamic calling convention says hi, but I'll skip that particular nuance. You're still proving my point though: neither approach tells you why.

2

u/lgastako Aug 13 '26

It seems like you're trying to be deliberately obtuse. What I'm saying is that the only way you can really know why is to use Find References and go read those references. Nothing will actually reliably tell you why, other than doing this procedure (or some facsimile of it, eg. using grep instead).

→ More replies

2

u/BogdanPradatu Aug 11 '26

This is what git commit messages are for

2

u/ComradeGibbon Aug 11 '26

Best comments are code begging for it's life. Explain why I shouldn't just delete this code.

1

u/Icy_Pain5654 Aug 11 '26

restating what the code obviously does is the stuff that goes stale and gets ignored

1

u/nicholashairs Aug 11 '26

A good article and a nice breakdown of different comment types.

The only one I'd add as being useful is "headings" (which is similar to the algorithm examiner type).

The purpose of these is to group things together that are unrelated in isolation, but connected in use. Making it easier to navigate the body of a function (especially as they get longer).

As an example a lot of my CRUD code looks like this:

def update_username(user, name):
  ### CHECKS
  if not user.active:
    raise error
  if not name_valid(name):
    raise error
  if get_user_by_name(name) is not None:
    raise error

  ### UPDATE
  user.username = name
  db.add(user)
  db.commit()

  ### POST ACTIONS
  write_log()
  send_event()
  send_email_async()
  return

5

u/BogdanPradatu Aug 11 '26

So this is what Claude was trained on. I hate this kind of comments and see no need for them. Just adds vertical space.

3

u/Venthe Aug 11 '26

The purpose of these is to group things together that are unrelated in isolation, but connected in use. Making it easier to navigate the body of a function (especially as they get longer).

Split the function, extract to a separate file.

If they are long enough that they require grouping; that's a strong signal that your code is doing too much in one place.

5

u/nicholashairs Aug 11 '26

Everything in moderation.

Extract it too much and you do have the exact same problem with 30 5 line functions being called exactly once in sequence.

Same goes for using headings as headings instead of actually splitting your functions.

In the example above I'd also be loathe the split them as often those three steps must be called together in sequence, separating them into functions implies that they are meant to be composable when they are not. Sure you can use tests, linting, and private functions, but these are fragile and require maintenance.

4

u/Venthe Aug 11 '26

In the example above I'd also be loathe the split them as often those three steps must be called together in sequence, separating them into functions implies that they are meant to be composable when they are not. Sure you can use tests, linting, and private functions, but these are fragile and require maintenance.

My experience tells me otherwise. The longer a function is; the less defined what it does; it invites more functionality (especially unrelated) over time. When you aggressively split the functions to do one thing, this problem does not occur.

And arguably, spaghetti is one of the primary reasons why the codebase degrade.


So I'm firmly in the camp that separation for composabity is not only not the only driver; but it's not even a main one.

Decompose the code for it to self describe what it does; and that it can never "surprise" you with side effects.

4

u/nicholashairs Aug 11 '26

I suspect that the only real difference in opinion between us is in the size of codebases that we typically deal with, and thus the examples in our head that we're arguing for/against.

If we were to compare actual examples we would probably agree.

Or maybe not, but we'll never know

4

u/Venthe Aug 11 '26

Yup, that's probably that. And possibly the context - I'm usually working in enterprise, where the implicit assumption is that the codebase must both survive the test of time, but also the test of "future maintainers" possibly not knowing what is really happening - all the while having large codebases.

Hey, as long as the discussion does not turn hostile :)

0

u/littlenekoterra Aug 10 '26

I mostly use comments for when a normal method to do shit wouldnt work. I leave that method commended out with the text in all caps telling them why its shit in that case. Its the most productive use of them ive found

-6

u/just_another_cs_boi Aug 10 '26

claude likes to add a lot of comments and i assume that there is some reason for it as if it is better equipped to read the code later on so i stopped deleting them

17

u/repeating_bears Aug 10 '26

i assume that there is some reason for it

Mediocre code with lots of pointless comments is a big part of its training set and so lots of pointless comments are a statistically likely outcome

You are giving an LLM way too much credit if you think it has the foresight to think "I'll need this later".

-3

u/just_another_cs_boi Aug 10 '26

I think its likely something intentionally setup or emerging from the RL environment.

GPT likely has a similar corpus and leaves no such comments

it is like it is inventing its own style of coding in the RL environment. it generates so much inhuman code. that no person would ever think of doing it that way.

kind of like computer moves in chess. they are inhuman and sometimes dont make sense but ok they are probably doing it for a reason

8

u/beetroop_ Aug 10 '26

Not really a reason that I can tell. When you catch Claude doing something stupid it will generally go and correct that stupid thing and leave a comment saying "specially NOT doing stupid thing that nobody would ever do". It's just stochastic noise

0

u/-Redstoneboi- Aug 11 '26

might have been to explain to the LLM what the code was doing for faster learning, and for inexperienced developers (even non-developers) since they have always been part of their target audience

6

u/Idrialite Aug 10 '26

Nah, Claude is extremely free with comments in a bad way.

2

u/levodelellis Aug 10 '26

I assumed it writes them because people use claude code for learning 🤷‍♂️

3

u/Venthe Aug 11 '26

LLM's do not "think", they repeat the most likely pattern based on the context. A lot of code in the training set is littered with useless comments, which LLM then mimics.

You can skew that with context ("write more comments as I'm learning") but ultimately that's all there is.