TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

On Comments in Code

179 点作者 nikbackm将近 4 年前

45 条评论

crazygringo将近 4 年前
Another use for comments: to document the strategies you tried and why they failed.<p>In other words not just the &quot;why&quot; but the &quot;why not&quot;.<p>Many times I&#x27;ve gone back to code I&#x27;d written previously, it seemed overly complicated, I replaced it with a simpler version... that failed... that reminded me that was what I&#x27;d tried originally and then replaced it with the more complicated version for a good reason.<p>So now I have a new rule: every time I try a simple approach and it fails and I replace it with a more complicated one that works, I add a comment explaining the previous strategy and why it didn&#x27;t work.<p>Hilariously, some of these have grown to <i>several</i> failed attempts. &quot;Tried A library but it has a critical bug where B happens. Then tried C function but it also has a bug where D happens. Using external command E doesn&#x27;t work because F...&quot;<p>But hey -- neither I nor anyone else will try to reprogram something simpler. Or we can check if the library mentioned still has the bug in question.
评论 #27524477 未加载
评论 #27521803 未加载
评论 #27521813 未加载
评论 #27522160 未加载
评论 #27526130 未加载
评论 #27524528 未加载
评论 #27525162 未加载
评论 #27522193 未加载
ElijahLynn将近 4 年前
The author touches on this a bit but I want to state this really simply:<p>Codes needs &quot;why&quot; comments, not &quot;what&quot; comments. The &quot;what&quot; can be done by self-documenting code, _most_ of the time. You still need to write &quot;what&quot; comments sometimes, don&#x27;t rule it out completely. And you routinely need to write &quot;why&quot; comments, self-documenting code will never provide the context of &quot;why&quot;.<p>Write more &quot;why&quot; comments.
评论 #27521588 未加载
评论 #27520104 未加载
评论 #27519884 未加载
评论 #27520378 未加载
评论 #27522701 未加载
评论 #27521863 未加载
评论 #27519866 未加载
redact207将近 4 年前
The thing that made my code 1000% more readable has been code reviews with a team that gives a damn.<p>When reading their code I&#x27;ll add feedback to parts I don&#x27;t understand (why do we need this cache invalidation, why do we use a worker pool here instead of throttling requests etc).<p>I find that questioning sits in the back of my mind when I write code - almost like a pair coder - to the point that I try to preempt questions like this by adding it as a comment.<p>Similarly for anything that&#x27;s publicly accessible like public functions&#x2F;properties&#x2F;interfaces&#x2F;classes, my goal for codedoc comments is to prevent the consumer (me or my team) from having to open the code to see what it does and how to consume it. If they can use it with just intellisense then it&#x27;s a win.<p>Just like code readability and design, I&#x27;m seeing comments as another tool to communicate intent that can&#x27;t always be communicated by code alone.
crazygringo将近 4 年前
&gt; <i>If you wonder what the method does, or what the valid input range for a parameter is, you are better off just reading the code to see what it does.</i><p>I couldn&#x27;t disagree more.<p>I was recently programming a library where some parameters could be 0 or greater, some parameters necessarily greater than 0, some parameters could be Infinity, others couldn&#x27;t...<p>Similarly, if one parameter is set to zero than another parameter will have no effect...<p>JSDoc kept the whole thing sane. &quot;Reading the code&quot; would take several minutes to figure out the answer in each case, which would be wasted time in my book.<p>JSDoc is awesome. Not every function needs it, but plenty do.
评论 #27521637 未加载
评论 #27524067 未加载
评论 #27521545 未加载
评论 #27522218 未加载
评论 #27527161 未加载
评论 #27521870 未加载
mpoteat将近 4 年前
On the contrary, I find standard JSDoc and its variants to be an excellent tool for internal documentation. With hovering support in modern editors, it allows context explanation in a very streamlined and human way.<p>The author mentions for preconditions to just “read the code”. I consider this bad advice. If using an external library, would you rather hover over the method and see its conditions, or would you rather crawl into the third party source code?<p>I recommend that you treat the internal structures of your code as reusable third party libraries, and not assume that anyone will be familiar with it or how it’s used.<p>Often my JSDoc comments take up more vertical space than the code itself, sometimes even with ASCII tables or example usage code. I believe this is one of the best approaches to documentation, especially paired with a automated documentation site generator tool.<p>Code is read much more than it is written. You need to think like a writer and consider your audience.
评论 #27520674 未加载
评论 #27527177 未加载
评论 #27520376 未加载
simonw将近 4 年前
I care much more about revision history than I do about comments. When I&#x27;m trying to figure out code I do it in &quot;git blame&quot; mode - what I&#x27;m hoping for is a single, atomic commit that links back to an issue thread. Ideally that issue thread will have all of context I need to fully understand the change.<p>This works great in codebases that are designed to be read in that way, which is why I&#x27;m so keen on every commit combining tests, implementation, updated documentation AND a link to the associated issue thread.<p>I&#x27;ll sometimes open an issue seconds before I make a commit, just so I can have an issue number I can associate the commit with. This is great for adding commentary later on - I might post a comment on an issue thread a year after the commit that help clarify some useful detail that, with hindsight, I should have recorded.
评论 #27521393 未加载
rav将近 4 年前
Sometimes, as you become a better programmer, a comment that you thought were a &quot;why&quot; comment is now clearly a &quot;what&quot; comment. One programmer&#x27;s &quot;magic super-efficient pointer gymnastics&quot; in C is another programmer&#x27;s standard idiom. When working on a large project as a team, most of the project may be run-of-the-mill code for most of the team, and so it doesn&#x27;t warrant &quot;what&quot; comments. However, there will be times when you have to introduce coding idioms that are foreign to everyone on the team, in which case a &quot;what&quot; comment may be warranted.<p>For example, a standard 5 year old React codebase probably used to contain a lot of class-based components and now is probably switching to function-based components with hooks. I know the first time I did a code review on my colleague&#x27;s code that introduced some weird hook concept - I asked for some more comments to explain what magic was going on. I would probably not ask for such a comment today now that everyone is more or less familiar with hooks and function-based components.
jakequade将近 4 年前
&gt; I didn’t need comments if I wrote self-documenting code.<p>More than any other approach to coding (x-based-development etc), this has come up most frequently for me personally, and it astounds me how many people have this mentality.<p>Comments are a way to break out of whatever terse syntax your given language requires and speak directly to the developer. A single comment can house so much more context and insight the best-formatted code could ever hope for. When the only downside is some holier-than-thou idea of &quot;I <i>shouldn&#x27;t</i> be doing this&quot; (despite the fact you clearly need to), I&#x27;m surprised so many people fall for this terrible mentality.
TrianguloY将近 4 年前
There are 4 main types of comments I use:<p>- javadocs: at the top of the function. Explains what you need to expect from it, very useful when autocompleting (yes, you can go read the code...but that&#x27;s slow)<p>- block description: before a bunch of lines. Explains what they do without need to read and understand them all, so you can read them faster.<p>- line description: at the right of a line of code. Explains the use of a specific variable, the reason you used a function call, etc.<p>- flow descriptor: the line after an if, an else and other path divisions like while or for. Explains why the code took that path. Useful when you need to understand the context of a specific line.
probably_wrong将近 4 年前
I&#x27;d like to argue against the author&#x27;s disdain for javadoc-like comments.<p>&gt; <i>If you wonder what the method does, or what the valid input range for a parameter is, you are better off just reading the code to see what it does.</i><p>I feel that this is a very inefficient approach to coding. If you tell me what the function does, what its valid inputs are, and what it returns then I don&#x27;t need to look at the code at all.<p>More so when I&#x27;m collaborating with people outside my area of expertise: a colleague of mine wrote a function to &quot;convert molecule SMILES into their neutralized form&quot;. What does it do? Beats me, I&#x27;m not a chemist. But thanks to the comments I don&#x27;t need to know, and I&#x27;m grateful for that.
评论 #27520286 未加载
评论 #27520152 未加载
citrin_ru将近 4 年前
I come to a conclusion that the main reason why some programmers argue against comments is just laziness. Writing comments requires an effort. Being smart they can find multiple reasons why their don&#x27;t have to do this.<p>Of course it is possible to intentionally create a harmful comment, but if you trying to write a useful comment it is likely will be useful for most readers. In my career there was a lot of situations when a small comment would have saved me time - I&#x27;ve spend many minutes and even hours to discover something a code author knew but was too lazy to put into comments. I don&#x27;t remember a single case when I suffered from an outdated&#x2F;incorrect comment (though in this discussion such situations are mentioned).
js8将近 4 年前
I suspect this &quot;no comments&quot; movement (which roughly argues that comments are hard to maintain, and you should avoid comments in the code, as writing clear code, and naming things properly, is enough, and if you have to comment, you should do it in organized doc strings) ultimately came from the idea that we will have &quot;code refactoring tools&quot; that will modify our code to be better and cleaner and it will increase our productivity. Such refactoring tools might understand the code itself, but they have a hard time with human language of comments.<p>I always hated that sentiment of &quot;no comments&quot;, although I share the wish of computers understanding our code better. I think the refactoring tools didn&#x27;t really live up to the promise, because they require the discipline of writing everything in the code in computer-readable format, otherwise they will leave fragments of wrong documentation in their wake. One of the benefits of human language is that you can easily create a DSL (concepts and terminology), and the refactoring tools usually cannot handle custom DSLs (much less vague ones) very well (seems like a strong AI problem).
javert将近 4 年前
I have a personal rule: If I need a comment, it goes at the beginning of the function.<p>This neatly groups the comment with the code it applies to.<p>Occasionally I have to make a function &quot;just&quot; for this grouping purpose, but that&#x27;s fine.
评论 #27520103 未加载
评论 #27520878 未加载
bregma将近 4 年前
I have never cursed an author for having too many comments. There are many cursed developers out there after my long career.
评论 #27522234 未加载
评论 #27520582 未加载
slver将近 4 年前
I&#x27;m quite irritated by this train of thought &quot;JavaDoc is useless because you can write a useless JavaDoc&quot;. Can&#x27;t we get at least past elementary logical fallacies.
Loic将近 4 年前
In scientific software, from my experience, we need a lot of &quot;javadoc&quot; like comments because you push data into functions which are basically equations. This means that you need to document the units (if not in SI), the assumptions, etc. Basically, the comment block is explanation of the equation.<p>I was bitten many times thinking &quot;yes, this is the equation (21) of the well-known paper, no needs to comment&quot; to then fall flat on the nose because this was well-known to me, not the other engineers coming from another field, an assumption was there for let say a concentration of a chemical in the formula but then it was used in another context where the assumption does not make sense, etc.<p>For all the &quot;bit-pushing&quot; part of the software, opening files, reading data and so on, it is way easier to have self documenting code.
da39a3ee将近 4 年前
I find Rust crate code to be quite difficult to read sometimes because it contains a lot of comments and executable examples destined to be incorporated into auto-published (and auto-executed) documentation. That&#x27;s a fine thing of course, but it would be nice if there were facilities to see &quot;just the code and code comments&quot;.<p>A somewhat random example is <a href="https:&#x2F;&#x2F;github.com&#x2F;ogham&#x2F;rust-ansi-term&#x2F;blob&#x2F;master&#x2F;src&#x2F;style.rs" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;ogham&#x2F;rust-ansi-term&#x2F;blob&#x2F;master&#x2F;src&#x2F;styl...</a>
评论 #27521794 未加载
discobean将近 4 年前
Not always, but I noticed I often find I write my comments first on what I want to achieve like a sort of psuedocode in a very high level.<p>Then under each one-line comment I&#x27;d write the code that does what&#x27;s written.
ChrisMarshallNY将近 4 年前
Important topic.<p>Documentation, in general, could use all the help it can get.<p>I wrote up a long piece on this[0]. No one will read it, because it&#x27;s long. I&#x27;ve found that no one reads anything that is more than about a &quot;7 minute read,&quot; these days. Part of my documentation problem, is that I can get too verbose. It&#x27;s not a good thing.<p>[0] <a href="https:&#x2F;&#x2F;littlegreenviper.com&#x2F;miscellany&#x2F;leaving-a-legacy&#x2F;" rel="nofollow">https:&#x2F;&#x2F;littlegreenviper.com&#x2F;miscellany&#x2F;leaving-a-legacy&#x2F;</a>
评论 #27542746 未加载
SulphurCrested将近 4 年前
Sometimes code relies on some condition being true, where that condition can be reasoned about by the developer rather than at run time by the program they are writing. I don’t think such comments fall cleanly into either the “what” or “why” categories people have mentioned here – perhaps they are “how”.<p>In mathematical terminology, the condition may depend on some lemma or theorem the programmer proved to themselves when writing the code. (I say “lemma” and “theorem”, but this applies to any kind of complex business logic, or the state of a realtime system, etc.) For a lemma (fancy name for a small theorem), the reasoning can go inline in the code, as a comment. If it’s a theorem, a more substantial thing you proved to yourself when writing the code, it might be better put in a separate document which a comment in the code should point to.<p>The reasoning you used to show the code works is better off written down for those who follow than forcing them to think through the same logic again. And the act of expressing the logic in a comment will tend to flush out errors in that logic. Those are both good reasons to spend the time writing such comments, unless you don’t care about technical debt.<p>As a special case, runtime assertions often need a brief comment to explain why they must be true.
chowells将近 4 年前
Sometimes you come back to a block of code you wrote a long time ago and go &quot;what?&quot; enough times that you go ridiculously overboard documenting it just to create the illusion of understanding it quickly the next time.<p>I still don&#x27;t understand <a href="https:&#x2F;&#x2F;gist.github.com&#x2F;chowells79&#x2F;996f2749b088d287937e3eff11055522" rel="nofollow">https:&#x2F;&#x2F;gist.github.com&#x2F;chowells79&#x2F;996f2749b088d287937e3eff1...</a> on the first read, even with the ridiculous overdocumenting. On the plus side, it&#x27;s clear enough what it does, even though the details of &quot;how&quot; are hard to follow.<p>Still, if there ever was a case for documenting the &quot;how&quot; over the &quot;why&quot;, that code is it. It&#x27;s pretty easy to understand why that code exists. It&#x27;s actually quite hard to follow the details of how it does it. Those comments are excessive, but they do cut the time it takes to rediscover the &quot;how&quot; whenever I get curious.
piinbinary将近 4 年前
The way I think about it is that comments needs to provide information that is both new and useful, where &quot;new&quot; and &quot;useful&quot; depend on the audience<p><a href="http:&#x2F;&#x2F;jeremymikkola.com&#x2F;posts&#x2F;2021_03_21_useful_comments.html" rel="nofollow">http:&#x2F;&#x2F;jeremymikkola.com&#x2F;posts&#x2F;2021_03_21_useful_comments.ht...</a>
aequitas将近 4 年前
Code is for computers to make them do exactly what you want them to do, comments are for your co-workers (and you) to make them understand what you actually meant to achieve.
评论 #27519834 未加载
评论 #27520289 未加载
评论 #27520028 未加载
bachmitre将近 4 年前
I like comments to be an &quot;alternative&quot; way to read the code , e.g. understanding the flow &#x2F; logic solely by reading through the comments (and only having to look at the actual implementation &#x2F; code when more details are needed).
jerhewet将近 4 年前
Comments should never be &quot;what&quot;. They should always be &quot;why&quot;.
ferdowsi将近 4 年前
Most documentation in dynamic languages I&#x27;ve encountered (like JS) have been wordy attempts at documenting function arguments. This almost always falls short of the goal. Describing object shapes and types is difficult in documentation, especially in languages that mutate objects willy-nilly. TypeScript and mypy are really essential documentation tools for that reason; they liberate developers from the Sisyphean task of describing object shapes and mutations and lets them write documentation that is actually useful.
fdr将近 4 年前
I often weigh the value of comments -- I used to write more, now I write fewer -- by weighing odds of utility against decay into misinformation. Comments conveying something of high utility that is fundamental to the program and unlikely to change make the cut.<p>I save most of my remarks for commit messages, which are understood to be contemporaneous. This method requires the average commit message quality be high, otherwise, people are unlikely to think to run blame on the file, even though most text editors can do so effortlessly.
MichaelMoser123将近 4 年前
+1 for log statements as comments; at least these don&#x27;t tend to become obsolete. When looking at unfamiliar code i tend to trust log statements more than comments, for this reason.
aliasEli将近 4 年前
The author is not very positive about JavaDoc. I agree that using it everywhere is probably overkill, but when you are writing a library JavaDoc can be useful for documenting it.
chapliboy将近 4 年前
I use comments to break up a large block of code into smaller chunks to explain what is happening &#x2F; where we are in the process.<p>I used to be a firm believer in self documenting code, but that approach often led to a large number of functions that only get called once. So lately, I have been just putting a comment line where I otherwise would have refactored the code into a function, and I feel that it has made my code a lot easier to read, and understand.
评论 #27525366 未加载
评论 #27525658 未加载
iblaine将近 4 年前
&gt; Every time I come back to those parts of the program, I am happy I made the effort to add a comment – they have been very helpful!<p>Exactly. Rarely hear someone say there are too many comments in this code! And feel free to not stop at the docstrings. Nested loops, obfuscated 1 liners, business logic that required a cross functional meeting to understand, are all valid reasons to be generous with comments.
k__将近 4 年前
Half-OT:<p>What happened to literate programming?<p>Back in the CoffeeScript days, it&#x27;s creator adopted a literate programming format, which was basically Markdown with code blocks being CoffeeScript.<p>He talked about that as the future of programming. Whelp, CoffeeScript got killed off by ES2015 and the file format never caught on.<p>I know the concept of literate programming does come from Knuth, but I first heard about it with CoffeeScript.<p>Why did this never catch on?
评论 #27524570 未加载
评论 #27523749 未加载
d23将近 4 年前
The only thing I would add is that header-style comments are immensely helpful for &quot;chunking&quot; the code into distinct sections. I first saw this recommended in Code Complete, and it stuck with me, since I&#x27;ve seen it in a number of other domains. It&#x27;s a basic part of cognitive psychology that makes information processing and retention much easier.
评论 #27522108 未加载
OnlyMortal将近 4 年前
I recall having to write a set of long comments to explain a rather complex routine. When it got to code review we discussed the routine and I made the remark that, if I had to explain the code I’d written, it was probably too complicated to start with. Re-wrote the code to be simpler for the sake of maintenance.
forgotmypw17将近 4 年前
Whenever I&#x27;m not clear on something I wrote, I have to spend the time deciphering it, and then add a comment to save myself the time next time.<p>After a while of doing this, I get a sense for what kind of stuff I&#x27;ll find puzzling later and can comment preemptively.
ryanthedev将近 4 年前
I comment stack overflow links when using some random code I copied.
watwut将近 4 年前
Yeah because it is so much faster to read the whole method and all methods it calls then ... hower over it to quick read javadoc in popup.
spcebar将近 4 年前
&#x2F;* * DO NOT EDIT THIS CODE YOU MORON. * THESE AREN&#x27;T THE LINES YOU&#x27;RE LOOKING FOR. * MOVE ALONG. *
teknopaul将近 4 年前
My golden rule is inline with javadoc being largly useless.<p>Don&#x27;t ever add SBO comments.<p>SBO = Stating the Bleeding Obvious.
评论 #27525321 未加载
gen220将近 4 年前
antirez (creator of redis) has some good thoughts on this topic, that people here might find valuable: <a href="http:&#x2F;&#x2F;antirez.com&#x2F;news&#x2F;124" rel="nofollow">http:&#x2F;&#x2F;antirez.com&#x2F;news&#x2F;124</a>
antihero将近 4 年前
Or to put it more succinctly: Code is the what, comments are the why&#x2F;why not.
jpswade将近 4 年前
Tests should really fill this gap, not comments.
pmoleri将近 4 年前
I agree with most of the article. Explain the why and tricky parts. Attempt self-documenting code, don&#x27;t loose your head over it.<p>On other aspect, I can&#x27;t believe this lived for 6 hours without the mandatory quote: <a href="https:&#x2F;&#x2F;xkcd.com&#x2F;1421&#x2F;" rel="nofollow">https:&#x2F;&#x2F;xkcd.com&#x2F;1421&#x2F;</a><p>Enjoy.
anotherevan将近 4 年前
&#x2F;&#x2F; I&#x27;m honestly convinced the compiler ignores all my comments.
timdaub将近 4 年前
I try to never write a comment about anything that I&#x27;ve already written in code. I only add information that is necessary to know to run the code but is not in the code.<p>I do it like this as I think that conceptually duplicating code logic through e.g. comments can be dangerously imprecise. E.g. when someone changes the code (and not the doublicating comment), there are no checks in place for this mismatch of code and comment to be caught by e.g. a test.
评论 #27520312 未加载