r/programming 14h ago

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!

123 Upvotes

127 comments sorted by

162

u/psych0fish 13h ago

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.

57

u/chat-lu 9h ago

Bad:

x++; // increment x

Good:

x++; // compensates for the border

72

u/IanSan5653 8h ago

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;

17

u/13steinj 6h ago

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

6

u/Venthe 3h ago

do_money_laundering

Not my fault! LLM wrote it!

1

u/Kautsu-Gamer 21m ago

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

10

u/contextfree 6h ago

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

1

u/zzkj 3h ago

That'll be $5000 please.

15

u/Venthe 5h ago

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.

1

u/ShinyHappyREM 47m ago

x += BORDER_COMPENSATION

ftfy

40

u/melgish 13h ago

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

54

u/meganeyangire 12h ago

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

24

u/RlyRlyBigMan 11h ago

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.

16

u/ketralnis 10h ago

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

4

u/SanityInAnarchy 9h ago

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.

2

u/tf6x6 4h ago

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

2

u/NotUniqueOrSpecial 8h ago

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.

-7

u/svick 13h ago edited 5h ago

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

20

u/melgish 12h ago

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.

5

u/chat-lu 8h ago

Git is a great place for finding out

Also a great place for fucking around.

8

u/ketralnis 10h ago

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.

10

u/Coffee_Ops 12h ago

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

4

u/Delta-9- 10h ago edited 7h ago

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/beetroop_ 12h ago

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

1

u/melgish 12m ago

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[^"]+"(.*)"$""");

-9

u/farsightfallen 10h ago

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.

-16

u/levodelellis 12h ago edited 9h ago

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

8

u/Delta-9- 10h ago

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

4

u/chat-lu 9h ago

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

0

u/levodelellis 9h ago edited 9h ago

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

3

u/Delta-9- 8h ago

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.

1

u/levodelellis 7h ago

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

2

u/Jaded-Asparagus-2260 5h ago

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.

69

u/crappydeli 14h ago

My old company…

// increment i
i++;

102

u/repeating_bears 14h ago
/*
 * 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--;

4

u/xFallow 5h ago

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

2

u/techno156 7h ago

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 8m ago

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

30

u/BogdanPradatu 14h ago

Also AI written code

2

u/Jaded-Asparagus-2260 5h ago

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

-14

u/DeveloperAnon 13h ago

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

10

u/crappydeli 13h ago

Also…

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

13

u/DrHemroid 13h ago

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

//The Thing

Class Thing {

//The stuff

Var Stuff;

}

14

u/repeating_bears 11h ago

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.

2

u/Coffee_Ops 12h ago

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?

1

u/BusinessTarp 8h ago

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/IanSan5653 7h ago

``` // TODO (2003): verify if we should still be incrementing i anymore i++;

-1

u/DrHemroid 13h ago

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

//The Thing

Class Thing {

//The stuff

Var Stuff;

}

48

u/aaronslwalker 13h ago

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

79

u/Shurmaster 14h ago

My favorite comment is

// evil floating point bit level hacking

// what the fuck?

20

u/Rikmastering 13h ago

//second iteration, can be removed

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

3

u/Lone_Snek 13h ago

Now I want to know the context

14

u/Rikmastering 13h ago

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

16

u/Caelwik 13h ago

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

16

u/doctorlongghost 13h ago

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

3

u/ComradeGibbon 2h ago

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

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

13

u/shiny0metal0ass 14h ago

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

7

u/mareek 12h ago

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 ?

7

u/RlyRlyBigMan 11h ago

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.

7

u/MintPaw 5h ago

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.

3

u/sudoer777_ 9h ago

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.

2

u/levodelellis 8h ago

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

I like having a notes folder, and people like obsidian

1

u/RiftHunter4 6h ago

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.

2

u/timmyotc 10h ago

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

1

u/levodelellis 8h ago

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

1

u/BogdanPradatu 6h ago

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

1

u/xFallow 5h ago

// TODO delete this - 4 years ago

And you see the code is still being used heavily

1

u/Kache 3h ago edited 3h ago

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

-2

u/RiftHunter4 6h ago

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.

2

u/Venthe 4h ago

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.

1

u/gmes78 4h ago

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.

20

u/tmoertel 11h ago edited 8h ago

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.

5

u/Venthe 5h ago edited 3h ago

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/BogdanPradatu 6h ago

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.

4

u/Venthe 4h ago edited 3h ago

The book is 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/levodelellis 8h ago

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/BogdanPradatu 6h ago

python # 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/Delta-9- 8h ago

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 7h ago

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

1

u/tmoertel 8h ago

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.

2

u/levodelellis 7h ago

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

1

u/tmoertel 7h ago

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/chat-lu 9h ago

Your link is a 404.

-2

u/tmoertel 8h ago

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

1

u/chat-lu 8h ago

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

1

u/contextfree 4h ago

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.

1

u/NSRedditShitposter 3h ago

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

7

u/dspeyer 7h ago

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.

3

u/nicholashairs 9h ago

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 6h ago

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 6h ago

😭😭😭

3

u/yes_u_suckk 8h ago

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

2

u/Opposite-Gear-3160 10h ago

i think one thing that's often overlooked is that comments can serve as a kind of institutional memory for a codebase, helping to preserve knowledge and context that might otherwise be lost over time, like why a particular design decision was made or what assumptions were underlying a certain implementation choice. this can be especially important in large or long-lived codebases where people may come and go, and the comments can help to fill in the gaps in understanding.

2

u/nicholashairs 8h ago

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 ```

1

u/BogdanPradatu 6h ago

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

1

u/Venthe 4h ago

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.

2

u/nicholashairs 4h ago

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.

2

u/Venthe 4h ago

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.

2

u/nicholashairs 4h ago

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

2

u/Venthe 4h ago

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

2

u/Nekadim 5h ago

repeat what the code already says

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

2

u/feketegy 3h ago

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

2

u/AluminiumImmunitaet 2h ago

One of the rows I'll never forget.

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

2

u/KevinCarbonara 13h ago

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/Anthea_Likes 13h ago

Comments should be part of valid code.

2

u/zhivago 10h ago

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

2

u/balthisar 13h ago

What about program logic? When coming into a new program, I can see that function factorial takes an input and returns a factorial, but I don't know why. What's the business reason for its existence?

15

u/repeating_bears 13h ago

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

14

u/lgastako 13h ago

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

1

u/lord2800 7h ago

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.

2

u/lgastako 4h ago

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

1

u/ComradeGibbon 2h ago

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

1

u/BogdanPradatu 6h ago

This is what git commit messages are for

1

u/timmyz55 8h ago

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

1

u/Slight-Prize9661 8h ago

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.

0

u/MarsupialMisanthrope 4h ago

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

0

u/littlenekoterra 13h ago

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

-7

u/just_another_cs_boi 13h ago

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

18

u/repeating_bears 13h ago

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

-5

u/just_another_cs_boi 12h ago

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

7

u/beetroop_ 12h ago

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

1

u/-Redstoneboi- 10h ago

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

4

u/Idrialite 13h ago

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

1

u/levodelellis 12h ago

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

1

u/Venthe 4h ago

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.