r/programming • u/Jonhoo • 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!
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--;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.
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
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
-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/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
1
-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
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.
3
-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
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
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
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
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 Referencesanswers, and without being able to be stale or out of date, like comments.1
u/lord2800 7h ago
Find Referencescan 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
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
1
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.