I worked with some Rails folks a while back who were utterly convinced that comments were to be avoided because it meant your code was not clear.<p>I agree that comments explaining 'what' is happening are mostly useless. Write clearer code. But 'why' comments are good. Most things can be coded up different ways. Tell me why you chose this way. Tell me about constraints that might not be immediately obvious. Let me know if indeed, it could be cleaner, but you were in a hurry (this is a thing that happens in the real world), or if it's that way for a specific reason.
> Because the culture of many development organizations undervalues comments, team leads (and managers) allow comments to get out of sync with the code—thereby increasing technical debt instead of reducing it.<p>Comment bit rot is inevitable, because comments don’t compile and can’t be tested. The only way to keep them in sync is by hand, which takes a lot of time and energy and is far from perfect. Of course,<p>> The first problem is that most developers are under great time pressure and don’t have the time to make the code so utterly clear that it requires no further comment.<p>So they don’t have time to write the code clearly, but they somehow magically have time to read and review all the comments and to keep them in sync with the code? And the reviewers too?<p>“If only developers worked harder…”. It’s nonsense.<p>Comments are great, they have an important place in software engineering, and I always regret when I forget to write some in a file or class. But they are not a silver bullet, and must be treated with suspicion, because there is no way to prove if they actually describe what’s going on. And that’s the same reason that they are hard to keep in sync.
More generally... my unwritten article is "Reducing developing bad beliefs about code by not listening to Uncle Bob".<p>He has been trying to say profound things for a long time now. He was super active in the XP community in early 2k onwards and he was nearly always saying things that I felt were a bit "off". i.e. there was a gem of an idea, but the idea was turned into some principle or rule that lacked nuance and context. Reality is, there isn't any fundamental rules/principles... just ideas, some ideas seem more universal than others, but these ideas are just a bunch of strategies you can use when approaching software development and depending on context they may or may not be good strategies.<p>In terms of commenting, some of this weird "wisdom" around commenting was fundamentally rooted in the idea you can't fix bad code with comments. People noticed that a lot of times where there was comments in "poor" code it actually was a spot where you could do some kind of refactoring to make the code clearer. Eventually this morphed into "If you need to comment your code you have failed" type sayings. However, there was plenty of people advocating commenting to explain things the code can't tell you, but too many were swayed by "commenting is failure to write good code" that they threw out some of the reason why people like to put comments in. Many in their first 10 years of coding really want guidelines and rules and principles and argue strongly for things they have found effective compared to how they approached coding previously. But these things you learn are almost never universal, even if you can see/argue how you could apply it to all kinds of things, other approaches might actually work better, or might work better in different contexts.
Seems like an appropriate time to share my 4 reasons to leave a code comment:<p>1. An odd business requirement (share the origin story)<p>2. It took research (summarize with links)<p>3. Multiple options were considered (justify decision)<p>4. Question in a code review (answer in a comment)
Comments are <i>critical</i> to long term project quality and consistency, but they're always going to rot until tooling starts taking them seriously.<p>For instance, it's great that code reviews have become standard practice at most organizations and for many projects, but the tooling for those reviews almost always rely on showing the few lines above and below a code diff. The reviewer has no convenient way of seeing how the changed code may conflict with any applicable comments unless the comments happen to be within those few nearby lines or the diff happens to include comment changes. Even then, the big picture is out of view and rot is still likely to seep in.<p>It would be nice if incoming developer-support AI could start tackling this, by surfacing impacted comments and even "linting" them for applicability and accuracy.
I always write comments, even on code I've written myself it comes in handy.<p>6 months later I wont remember why the "easy" solution wasn't the path that was taken, or some complexity that needed special handling in a single case that was discovered through a few hours of debugging.<p>Sure you could write perfect code, but writing out your thought process helps tremendously with understanding a thought process and getting up to speed far faster.
Having done some "code archaeology" in my past, I loved coming across a good comment block, with clear rationale as to why something was done, which looked incorrect if you only had the code.
I’ve always pushed back against the “no comments, they go out of date” sentiment.<p>Comments aren’t milk, they don’t just go off, developers let them go out of date.<p>As others have said, comments should be used to add why, to give context.
I feel statements like:<p>"...team leads (and managers) allow comments to get out of sync with the code..."<p>reveal a fundamental misunderstanding of how software organizations generally work.
I don’t know how many people have worked on a project with JavaDoc, but it really is an incredible boon, as the OP notes, and will make you want to comment everything with quality. People talk about “poorly documented code”, which thy acknowledge is a weakness, but they don’t connect that the comments cover the documentation. If you’ve ever joined a place with turnover, having you own documentation on the magic mega project is really valuable. Yes, comments can lie, but you’ll figure it out when the call doesn’t do what it says on the box. The benefit is that you jump ahead on all cases where the comments are truthful and the code still works without issue. You might also discover that someone already written a method or tool you thought you needed. There’s huge savings from having comments and documentation. Comment and documentation can even be a way out of the bus problem.
Most programmers I’ve worked with can write some code within minutes of a discussion but stall when they’re asked to comment or to vocalise what they’re doing and why. They believe the reason is that they are working at such an abstract level that it’s not easy to put into words until some higher-level concepts have been coded. Of course, at that stage, comments are not added either. Discussing the code for commenting at this stage often elicits a response which results in throwaway comments or another writer’s block. Everyone loses.<p>My personal solution has been to approach code documentation as programming in one’s native language, or as is often done, in English. Learning to comment is given the same importance as learning to code. Comment maintenance is given the same priority as code maintenance. Explaining the actual function and expectations by comment is the essential part of writing code that expresses the functionality.<p>Comments are given similar weight as code. Comment design is considered at an early stage. And comment maintenance is equally as important as code maintenance.<p>Why do we talk about coding rockstars but don’t we talk about commenting rockstars? This isn’t anti-agile or anti any methodology if it’s presented as an integral and essential part of the task.<p>Often, when mentoring such processes, the act of commenting liberates insights that may have only appeared during failed product testing.<p>Of course, learning to comment effectively is learning to communicate effectively. Metrics for effectiveness are often elusive and people are rarely paid for lines-of-comments, so this is always a hard sell, unless it’s understandable to be a core coding activity.<p>We see the same thing in related areas, like logging. Unless you need to solve a problem with the help of accurate logging data, you don’t see the need or utility of logging anything. As with comments and code, logging also needs consideration and maintenance.<p>Learn to code
Learn to comment
Learn to log<p>These mantra won’t come from above, so need to be learned and understood.
The article misses the most effective comments - git commit messages.<p>Regular comments are subject to bit rot - they get less true with time. Unless actively maintained - eventually all comments lie.<p>Git commit messages maintain themselves. If a line of code was changed - the git blame annotation will change. So you know exactly what the context was and exactly which lines the comment relates to. It provides context (you can see in the commit what else changed with it), and if you include the JIRA task number and a short description - it provides the WHY.<p>IMHO the most important skill for writing understandable code is splitting the commits into sensible pieces and writing good commit messages.
The Code as Documentation crowd produce beautiful code, and I follow much of the practice, but while it is good at self-documenting what is happening, it's hard to get the why entirely into code without being obtuse. Especially when working around framework limitations. This becomes very important in the maintenance phase.<p>I can see you getProductCollection, I know what that does, but why do you do nothing with it? Oh it's because it needs to be loaded before presenting the cart, and there's a bug in the framework that fails to do so in this scenario.<p>Also business requirements can be reaaally asinine, a makeThisParticularButtonGreenSeeMeetingNotes20122023() would be pretty lame but that is often required information for a developer revisiting a feature and wondering if something was a bug or intended.
This feels like somewhere that GPT could actually prove helpful- I don't love GitHub CoPilot all that much, but a linter that could warn and suggest where comments aren't matching the code could be helpful to keep 'comment rot' at bay
Cutting all comments under the false certitude that if code is clear you shouldn't need any is as dogmatic as leaving a class comment explaining the whole file whether you needed it or not.<p>Stop being so dogmatic about comments and do what works for your team.<p>Such a flame war territory.
I generally tend to think of code as "encoding" or formalising intent. If the intent is obvious from the code comments are usually not necessary, but if the intent is hard to decode when glancing at the code, then I comment on it.<p>Sometimes things are just complicated and they require explaining the intent to help the reader understand the code. It also helps spot bugs or allows someone smarter than me to rewrite it in a better way (for different axes of better)<p>There are other situations where comments are useful that are covered elsewhere in the thread, too.<p>So, I've gotten some good ideas on how to improve my code comment etiquette!
Some of the aphorisms and cheap philosophies people apply to programming are so contrary to common sense it makes me wonder how they got into the business of writing programs to begin with. Writing code without comments is like writing a novel with no exposition. Writing code with too many comments is like writing a novel that is all exposition. Aristotle
remains correct in the world of software insofar as moderation is still key. You want just enough exposition so that your reader knows what the hell is going on and not so much that they get bored.
I have come to a "middle ground," when structuring and commenting code.<p>First, the code needs to be fairly clear, but not "stupid" clear. I have had people tell me not to use idiomatic Swift, because "a JavaScript programmer can't understand it."<p>In some cases, this may be necessary, but not in mine.<p>The #1 consumer of my code, is Yours Truly. The wonkiness doesn't bother me, but sometimes, I may not be aware of <i>why</i> I did something (that may not be "idiomatic," at all).<p>That's why I may write a quick comment, like so:<p><pre><code> showThrobber()
// The reason for this, is that we need to give the throbber time to show up.
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(20)) {
</code></pre>
That explains the awkward use of an "asyncAfter()" method.<p>It was the result of me, wasting a good half hour, trying to figure out why the screen didn't change. I saved future me, a half hour (and also a signpost for "improvements needed").<p>I write about my approach to documentation, here: <a href="https://littlegreenviper.com/miscellany/leaving-a-legacy/" rel="nofollow">https://littlegreenviper.com/miscellany/leaving-a-legacy/</a>
i think comments can be very useful. for example, look at the c function strlen:<p>int strlen( char * s );<p>the following comment pretty much describes what it does:<p>- if passed a null-terminated string, returns the number of characters in the string, excluding the terminator<p>- if passed a null pointer, or an incorrectly terminated string, behaviour is undefined<p>these are the kind of comments i like to see
I think the real way you can reduce technical debt is by valuing code less, not comments more.<p>Comments are vital, but I prefer everything be refactored to make the code the comments, which only happens if you get naming right, the language, libraries and the frameworks don't fight you. Which is a lot of ifs. Even then you need the comments to label parts of code that are exceptions to normal practice, or to fix particularly subtle bugs so that you prevent regressions from happening. (If you want tests to do that, it doesn't obviate the need for comments - you probably want the comments in the code and the test, because you don't want it to be standard practice when you are editing code to discover a new all the failing test cases when you make a change)
It would be really nice if there was any data this article could could cite, pro or anti comment to see if it makes any measurable difference to your team’s market competitiveness.<p>The data they cite on TODO items isn’t relevant as the experiment lacks any controls and is thus non-scientific.<p>The best we can do given the dearth of data is consult the market for answers. There are successful software companies/projects/individuals that subscribe to either philosophy (sometimes simultaneously) and the market doesn’t seem to care as it does about how good the product actually is. Stuff like this is bike shedding at best, at worst it’s a kind of virtue signaling to some group in an attempt to appear as a blessed expert.
Used sparingly comments can be very good. One should comment non-obvious things or gotchas. Where it goes completely of the rails is when programmers are forced to write comments in mandated places. One ends up with a code base where half of the code consists of comments that point out the absolute obvious.<p>DatabaseConnection connnection; // Connection to the database.<p>// Write a log line when the system is intialized
logger.info("The system was initialized successfully.");<p>When I see such comments I am severely tempted to conclude that if one is going to have a policy on comments forbidding them would do less harm then mandating them everywhere.
I was frantic code commenter in my youth because I wanted to give as much information to other people as possible but as I became SR developer I dropped them altogether. Especially after I moved into Go. Nowadays, I comment only in two situations:<p>1. if it is important to explain WHY something is done in a way it is done<p>2. if there is some related or directly connected code far away that the person might miss or cannot know about and how this code influences it. Writing self-explanatory code nowadays is a standard. An era of newbie spaghetti code is long gone so no need to explain the code itself.
As someone who took ownership of a large codebase from a genius former colleague who rarely explained himself, the only reason we kept the code was my insistence on replacing cryptic code 1-liners with easier to read/maintain multi-line expressions that had terse-but-readable variable names and //inline comments.<p>The team ended up expanding the codebase quite a bit before that technology stack was retired a couple years later. Not sure if it would have survived without that refactoring.
Comments are vital. good comments are a multiplier. I have never been put off because of comments except when there is a wall of text explaining the entire file.....no...just no.
I found that higher-level comments (docs), explaining the overall logic, design choices and use cases are often missing. Developers should be given time to write those.
There is a difference between you writing code for library and general purpose app. When you write code for an app, you are bound to change the code frequently than you are writing code for library, so while I think there could be merit in putting comments for library, i dont think it will counter productive to write comment for your app code, as it is pain in the wrong side to keep both code and comment consistent
Now, we can delegate such tasks, comment every functions, classes and variables to GPT-3 davinci or Codex with clever prompt as clear as possible, (ELI5, reasoning, anecdote, storytelling, metaphors, etc). I think that would definitely useful AI use case.
The only thing that can potentially make less technical dept is code reviews eg forcing multiple people to look at every new piece of code preferably also have automated tests and CI.<p>The code can have comments or not, it's more of a preference.
The link at the end of the article to the JVM written in Go is a cool project. The GH project is at <a href="https://github.com/platypusguy/jacobin">https://github.com/platypusguy/jacobin</a>
Loving all the pro-comment comments - way to go Hacker News! We’ve come a long way since the days of everyone posting that static typing is the devil, and that my code ‘documents itself’.
For fun, I asked ChatGPT to write code documentation for a small sample class (C# xml docs in this case). It did an incredibly good job at this. I don't really think this type of documentation will be necessary in the future as it can easily be inferred by AI. I think that extends to code comments as well. Perhaps it is too early for such guidance but I suspect over time the pendulum will swing to not documenting / commenting any code which can be inferred from the code itself (even if the code would require considerable concentration to understand).<p>Of course, it is impossible to infer from the code <i>why</i> something was done so this will always be needed.
I love seeing comments in the code as they are usually the best entertainment I get all day. Especially when the code below it pretty much doesn’t do what it says anymore.
i think what gets missed is that it depends. there are languages and domains where it is possible to write sufficiently succinctly and clearly that you don’t need comments.<p>there are also places where you might want to explain the “why” even if the code is clear.<p>relying on comments to understand the “how” has been a smell in every codebase i’ve seen.
Unpopular opinion, but in the words of Linus, I have my asbestos underwear on so flame away:<p>* Comments are excuses<p>* They're used to validate the existence of crappy code<p>* They do nothing for you in production<p>Instead:<p>* we commit to writing log messages... which are sort of like comments, but they work in production