42 ms·
On Comments in Code
- forgotmypw17 5y agoWhenever I'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. After a while of doing this, I get a sense for what kind of stuff I'll find puzzling later and can comment preemptively.
- aequitas 5y agoCode 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.
- jaywalk 5y agoCode involves names of methods and variables which can greatly aid in understanding as well. I've always maintained that comments should only be in code to explain something that is not obvious. If you're calling the SaveUser function and passing in a new User object that you had just created, a comment of "Save the new User object" adds nothing but noise.
- krylon 5y agoA comment like "This method opens a separate database connection so as not to mess with the ongoing transaction" or some such would be rather helpful, though.
- jaywalk 5y agoWithin the code I write, I can't think of a scenario where that wouldn't be obvious. But if it is indeed not obvious, then I agree that would be a helpful comment.
- aequitas 5y agoMost code (and the effects of removing/refactoring it) are not that obvious at first glance. But I agree, if your code is as simple and self documenting as that a comment like that doesn't add anything. But a lot of the intention cannot be expressed in code alone. This is where comments help enormously. It allows me to review the code and compare it to the writers (often me) intent and spot bugs or refactor if needed. Without it a lot of knowledge has to be rediscovered again.
- pjerem 5y ago- Do you SaveUser to the database directly or do I have to somehow call something to validate the transaction ? - Once it’s saved, can I continue to use my User model or should I fetch the more complete one from the database ? - Does this even SaveUser to the database or on a temporary structure that will be fetched by our UserCreationBot ? - Does SaveUser checks if the username already exists or should I check myself before calling it ? - Does SaveUser checks that current user is allowed to create new users or should I check it before ? - What happens if SaveUser is called with a User with an empty password ? Does it means that the input is wrong or am I legitimately creating a user that can’t login?
- jaywalk 5y agoCheck the code of the SaveUser method.
- javert 5y agoI disagree. Code is not just for controlling the computer. Just as importantly, it's also meant to be read by humans. So, code should be written in a way that is easy for a human to read and understand. Code should easily and naturally show what it's intended to achieve 99% of the time. Comments should be used sparsely, and only to express things that must be expressed and cannot be expressed in code.
- bregma 5y agoAll code is literature intended exclusively for humans. Computers read machine instructions; they're incapable of reading code. Know your audience.
- jbay808 5y agoHumans wouldn't care so much about semicolons, but I do want the compiler to understand my code, too.
- hawski 5y agoHave you seen decompiled code? That's all that compiler cares about, it is not pretty.
- teknopaul 5y agononsense. code is intended for a computer by definition.
- pjerem 5y agoNo. Code is intended for your teammates. Compiled machine code is for your computer. If you were addressing a machine, you would be writing 0s and 1s, because o boy do the machine know how to execute those little ons & offs.
- retsibsi 5y agoPeople often insist on this point, and I still don't get it. Honestly it comes across as intentionally exaggerating a claim beyond reason, in order to make it sufficiently counterintuitive to sound clever. The point of the program is to get the computer to perform some task; the way we get the program into the computer is to write code. You can say we're writing code for the compiler if you want to be pedantic; or you can say we're writing code for humans too, which is a perfectly valid point. But what do you actually mean by insisting that no, the code isn't for the computer at all, it's solely for other humans? It's clearly the language we use to communicate with the computer to tell it what to do; the fact that there's a translation step (performed by the computer) between what we write and what the computer executes doesn't change that in any relevant way.
- ElijahLynn 5y agoThe author touches on this a bit but I want to state this really simply: Codes needs "why" comments, not "what" comments. The "what" can be done by self-documenting code, _most_ of the time. You still need to write "what" comments sometimes, don't rule it out completely. And you routinely need to write "why" comments, self-documenting code will never provide the context of "why". Write more "why" comments.
- Nicksil 5y ago>Codes needs "why" comments, not "what" comments. Indeed. While there are exceptions, "what" comments will usually only add noise thus making things more difficult. This isn't necessary: // Total count int total_count = 0;
- nicoburns 5y agoI find it's often useful to put a 'what commment' on a block of a few (2-10) lines of code. Then you can skim through the function without reading every individual line of code.
- isbvhodnvemrwvn 5y agoYou might as well be able to extract a method with a meaningful name then.
- ziml77 5y agoPlease no. Don't extract methods methods just to avoid using a comment. You end up making code more difficult to follow when you do that since you're now jumping somewhere else in the file and you're adding a lot of noise by having to pass the function's current state along as arguments to the new function.
- hackinthebochs 5y ago>by having to pass the function's current state along as arguments to the new function. But then the state being read and mutated by a block of code is explicit. The alternative is having to inspect the code to determine if and what state is being manipulated. The more code in a functional unit, the harder this gets.
- mpoteat 5y agoOn 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. 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? 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. 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. Code is read much more than it is written. You need to think like a writer and consider your audience.
- teknopaul 5y agonothing wrong with the tool, the issue is with the comments that exist and those that don't. getFoo() does not need a comment. if it does, (it shouldn't) and its JavaScript, JSDoc is a fine format. if getFoo() does need a comment, consider changing the code so it doesn't. Code is read much more often than its written: so be concise. If the docs can be automated by a simple tool, by definition, they were not necessary.
- nomel 5y agoI generally enjoy a brief description of the overlying concept, at the top of each function. I don't care to know how a function is implemented as much as rough details to help me navigate the new/forgotten code space/context. Usually, a quick example of usage, within some relevant context, is enough to push me in the right direction. If I have to read every line of implementation to know wtf is going on, then I'm probably going to have a bad time.
- iudqnolq 5y agoDepending on the context, I might mention if getFoo is expansive, is cached, talks to the network, or can throw.
- rav 5y agoSometimes, as you become a better programmer, a comment that you thought were a "why" comment is now clearly a "what" comment. One programmer's "magic super-efficient pointer gymnastics" in C is another programmer'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't warrant "what" 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 "what" comment may be warranted. 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'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.
- javert 5y agoI have a personal rule: If I need a comment, it goes at the beginning of the function. This neatly groups the comment with the code it applies to. Occasionally I have to make a function "just" for this grouping purpose, but that's fine.
- mpoteat 5y agoThis is also my practice. Any code that is complicated enough to require a special comment is also complicated enough to be its own function.
- javert 5y agoExactly my thinking. Very well said.
- truetraveller 5y agoThis is a nice rule of thumb. Works great for 90% of use cases. For the other 10%, it's "acceptable". I like it. It also discourages "what" comments, and encourages longer "why" comments. The biggest benefit is: standardization, and no need to think about comments again.
- probably_wrong 5y agoI'd like to argue against the author's disdain for javadoc-like comments. > 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 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't need to look at the code at all. More so when I'm collaborating with people outside my area of expertise: a colleague of mine wrote a function to "convert molecule SMILES into their neutralized form". What does it do? Beats me, I'm not a chemist. But thanks to the comments I don't need to know, and I'm grateful for that.
- watwut 5y agoTo me the above quote says that author never worked with anything more complicated or more big then simple crud web app.
- ozim 5y agoTo me it says that author is perfectly aware that people are not updating Javadoc comments or normal comments as well.
- pjerem 5y agoIf your method documentation is out of date, the problem is not about the doc. The problem is that someone on your team drastically changes existing methods behavior instead of writing new ones, and by doing that, is changing the behavior every historical caller expected. I really think that if your changes are so important that they need the doc to be updated, it’s probably that you should write a brand new method. Changes in an already called method should only concern implementation details.
- ozim 5y agoIt is not about my team. It is about people. In the world where team members last ~2 years and move on, expecting that documentation is left not updated is in my opinion perfectly valid assumption.
- aliasEli 5y agoThe 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.
- watwut 5y agoYeah 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.
- chowells 5y agoSometimes you come back to a block of code you wrote a long time ago and go "what?" enough times that you go ridiculously overboard documenting it just to create the illusion of understanding it quickly the next time. I still don't understand https://gist.github.com/chowells79/996f2749b088d287937e3eff11055522 https://gist.github.com/chowells79/996f2749b088d287937e3eff1... on the first read, even with the ridiculous overdocumenting. On the plus side, it's clear enough what it does, even though the details of "how" are hard to follow. Still, if there ever was a case for documenting the "how" over the "why", that code is it. It's pretty easy to understand why that code exists. It'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 "how" whenever I get curious.
- teknopaul 5y agoMy golden rule is inline with javadoc being largly useless. Don't ever add SBO comments. SBO = Stating the Bleeding Obvious.
- benrbray 5y agoSometimes what is obvious to the code author won't be obvious to the person tasked with maintaining it. Sometimes, the "obvious" code has a bug, but its intended purpose is no longer obvious. Commends for "obvious" things add redundancy, like error-correcting codes.
- jpswade 5y agoTests should really fill this gap, not comments.
- timdaub 5y agoI try to never write a comment about anything that I've already written in code. I only add information that is necessary to know to run the code but is not in the code. 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.
- jbay808 5y agoIf you have really good test coverage that might be okay, but otherwise, how do you know if the code is doing what it's intended to do? If I see a line that looks like it might be a bug, or an unnecessary duplication, how do I know if it's a mistake or not?
- ferdowsi 5y agoMost documentation in dynamic languages I'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.
- bregma 5y agoI have never cursed an author for having too many comments. There are many cursed developers out there after my long career.
- teknopaul 5y agoYou never lived through auto-javadoc?
- etripe 5y agoAh, the awesome flavour of Markov chain nonsense that is auto-generated docs. I think the existence of this phenomenon shows the danger of strictly adhering to policy that was written by someone who never suffers its effects.
- GuB-42 5y agoI have. And stripping comments before working on it is a thing I have done many times, on code I wasn't familiar with. The biggest problem is lies. If you don't update your comments, don't write them. If you know someone less careful than you is going to take over and not update your comments, don't write them either. And then, there are the redundant comments, the ones I see most often. For example - Don't describe the function both in the header and source code, it is a useless copy-paste that will never be updated correctly. (mostly for C/C++) - I know the syntax for declaring a constructor, thank you, you don't need to tell me that is is a constructor in the comments. And I can also guess that getX() gives me the value of X, no need to fill my screen with dozens of useless lines of comment. - I don't need a comment to know who did what. We are under source control and we have a "blame" command. - Don't use comments to disable code. Just delete it, it is not lost, we have history, and we are unlikely to need it anyways. But the one that makes me rage the most is something like "int time; // the time". Not only it is useless, but you are not giving the info I want: the fucking unit! I've seen it way too often, sometimes with far from obvious units, like tens of microseconds. So if you want to put a comment, at least tell us the unit. Or better yet, don't comment anything and make your variable something like time_in_ms, or define a type.
- ChrisMarshallNY 5y agoImportant topic. Documentation, in general, could use all the help it can get. I wrote up a long piece on this[0]. No one will read it, because it's long. I've found that no one reads anything that is more than about a "7 minute read," these days. Part of my documentation problem, is that I can get too verbose. It's not a good thing. [0] https://littlegreenviper.com/miscellany/leaving-a-legacy/ https://littlegreenviper.com/miscellany/leaving-a-legacy/
- ItsMonkk 5y agoOne of the key things that I believe is that the world has gone to far in the metric direction. Metrics lead to things like fake reviews, teaching to the test, and SEO. The only way to avoid this is to put your trust into people that you believe have good signal to noise ratios. While posting on HN I believe that your posts have good signal to noise ratios, so I will now henceforth go through your post history looking for quality content. This post was one such event. Because I viewed your content like this, length went from a cost to a value. I read the entire article(okay, I skimmed the code sections). Love the blog. It made my skills as a developer better. Not much to add, a benefit of the verbosity.
- ChrisMarshallNY 5y agoHey, thanks!
- piinbinary 5y agoThe way I think about it is that comments needs to provide information that is both new and useful, where "new" and "useful" depend on the audience http://jeremymikkola.com/posts/2021_03_21_useful_comments.html http://jeremymikkola.com/posts/2021_03_21_useful_comments.ht...
- simonw 5y agoI care much more about revision history than I do about comments. When I'm trying to figure out code I do it in "git blame" mode - what I'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. This works great in codebases that are designed to be read in that way, which is why I'm so keen on every commit combining tests, implementation, updated documentation AND a link to the associated issue thread. I'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.
- RandallBrown 5y agoDefinitely. Commit messages are updated with the code automatically. Comments seem to become out of date almost immediately.
- joppy 5y agoIsn’t this an argument for better code review, rather than against comments?
- d23 5y agoThe only thing I would add is that header-style comments are immensely helpful for "chunking" the code into distinct sections. I first saw this recommended in Code Complete, and it stuck with me, since I've seen it in a number of other domains. It's a basic part of cognitive psychology that makes information processing and retention much easier.
- da39a3ee 5y agoI 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's a fine thing of course, but it would be nice if there were facilities to see "just the code and code comments". A somewhat random example is https://github.com/ogham/rust-ansi-term/blob/master/src/style.rs https://github.com/ogham/rust-ansi-term/blob/master/src/styl...
- ridiculous_fish 5y agoI wish for a text editor that shows the comments to the side of the code, like in a split pane.
- crazygringo 5y ago> 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 couldn't disagree more. 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't... Similarly, if one parameter is set to zero than another parameter will have no effect... JSDoc kept the whole thing sane. "Reading the code" would take several minutes to figure out the answer in each case, which would be wasted time in my book. JSDoc is awesome. Not every function needs it, but plenty do.
- kelnos 5y agoThe worst, though, is when a comment tells you the valid input range, but it's wrong, because someone later changed the code and didn't update the comment. While this doesn't happen frequently, I've gotten bit by it enough that I will generally at least take a cursory look over the function body to verify that the comment is still correct. I wouldn't say this makes the comment useless, but it does reduce the usefulness. And this might end up biting someone who has decided to trust the comments.
- deleted 5y ago[deleted]
- nytgop77 5y agoFull agreement. Unfortunatly it is a story, that is set to repeat 3 times. There is a similar tragedy of outdated documentation. And then the final part of the trilogy is named "outdated and even misleading naming" (vars/functions). In all cases, one should have same amount of trust as with weather forcast or politician's speech. Trusting 100% would be naive, but complete dismisall would be foolish as well.
- ravenstine 5y agoWhen I started out programming I was taught that the code should "document itself" and that comments were an anti-pattern to writing good code. It took me a few years realize how idiotic that was and deprogram myself. It's one of those things that sounds nice, but once you've moved beyond a certain level of complexity you realize how impractical it is. The fact is that "good code" is often in the eye of the beholder and not everyone has the same skill or vision, so they might as well write a comment about what something does and the intent behind it rather than leave others guessing.
- crazygringo 5y agoAnother use for comments: to document the strategies you tried and why they failed. In other words not just the "why" but the "why not". Many times I've gone back to code I'd written previously, it seemed overly complicated, I replaced it with a simpler version... that failed... that reminded me that was what I'd tried originally and then replaced it with the more complicated version for a good reason. 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't work. Hilariously, some of these have grown to several failed attempts. "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't work because F..." 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.
- macintux 5y agoI refer to this type of problem a lot when arguing comments are useful. No amount of code can document the code that isn’t there for a reason.
- pmoleri 5y agoOr you can write tests for every single not there case. Just bringing it up, I usually write lots more comments than tests. I also encourage my teammates to add comments. The problem is when one can't really explain why the simpler approach didn't work. That requires more research just to write the comment, but I think it pays off really quick.
- TrianguloY 5y agoThere are 4 main types of comments I use: - 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's slow) - 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. - 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. - 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.
- redact207 5y agoThe thing that made my code 1000% more readable has been code reviews with a team that gives a damn. When reading their code I'll add feedback to parts I don't understand (why do we need this cache invalidation, why do we use a worker pool here instead of throttling requests etc). 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. Similarly for anything that's publicly accessible like public functions/properties/interfaces/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's a win. Just like code readability and design, I'm seeing comments as another tool to communicate intent that can't always be communicated by code alone.
- slver 5y agoI'm quite irritated by this train of thought "JavaDoc is useless because you can write a useless JavaDoc". Can't we get at least past elementary logical fallacies.
- fdr 5y agoI 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. 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.
- k__ 5y agoHalf-OT: What happened to literate programming? Back in the CoffeeScript days, it's creator adopted a literate programming format, which was basically Markdown with code blocks being CoffeeScript. He talked about that as the future of programming. Whelp, CoffeeScript got killed off by ES2015 and the file format never caught on. I know the concept of literate programming does come from Knuth, but I first heard about it with CoffeeScript. Why did this never catch on?
- klyrs 5y agoI like notebook-style programming (e.g. Jupyter, Mathematica, etc) for this. They don't quite fit the bill, and for example, don't provide a mechanism to render into a clean library with unit tests extracted from the notebook. But I still hold out hope for a good cross-language system. Having read some of Knuth's literate code... good god that man is brilliant, but aesthetic language design isn't his wheelhouse
- twobitshifter 5y agoI think many programmers are not big on writing, you can see on this thread there are a large number that object to almost any comments at all, and support the assertion with the belief that comments go stale and won’t be updated because people can’t be bothered to write. I think the appeal of no comments is the quest for perfection in the source code - that you can achieve something that needs no explanation. In contrast literate programming nakedly admits the discovery of the solution and how code was developed and its imperfection. That said it has caught on some with data science and actually is an option with swift playgrounds.
- iblaine 5y ago> 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! 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.
- jerhewet 5y agoComments should never be "what". They should always be "why".
- deleted 5y ago[deleted]
- jakequade 5y ago> I didn’t need comments if I wrote self-documenting code. 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. 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 "I shouldn't be doing this" (despite the fact you clearly need to), I'm surprised so many people fall for this terrible mentality.
- discobean 5y agoNot 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. Then under each one-line comment I'd write the code that does what's written.
- pmoleri 5y agoI agree with most of the article. Explain the why and tricky parts. Attempt self-documenting code, don't loose your head over it. On other aspect, I can't believe this lived for 6 hours without the mandatory quote: https://xkcd.com/1421/ https://xkcd.com/1421/ Enjoy.
- anotherevan 5y ago// I'm honestly convinced the compiler ignores all my comments.
- MichaelMoser123 5y ago+1 for log statements as comments; at least these don't tend to become obsolete. When looking at unfamiliar code i tend to trust log statements more than comments, for this reason.
- bachmitre 5y agoI like comments to be an "alternative" way to read the code , e.g. understanding the flow / logic solely by reading through the comments (and only having to look at the actual implementation / code when more details are needed).
- SulphurCrested 5y agoSometimes 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”. 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. 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. As a special case, runtime assertions often need a brief comment to explain why they must be true.
- chapliboy 5y agoI use comments to break up a large block of code into smaller chunks to explain what is happening / where we are in the process. 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.
- spinny 5y agoSame here. The majority of my code is usually readable but still add comments on bigger chunks of code to split that code into logical sections, it's particularly useful when using a text editor with code highlight
- t-writescode 5y agoHow has your testing been impacted? I usually write several functions to isolate code for testing.
- Loic 5y agoIn scientific software, from my experience, we need a lot of "javadoc" 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. I was bitten many times thinking "yes, this is the equation (21) of the well-known paper, no needs to comment" 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. For all the "bit-pushing" part of the software, opening files, reading data and so on, it is way easier to have self documenting code.
- js8 5y agoI suspect this "no comments" 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 "code refactoring tools" 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. I always hated that sentiment of "no comments", although I share the wish of computers understanding our code better. I think the refactoring tools didn'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).
- OnlyMortal 5y agoI 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.
- citrin_ru 5y agoI 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't have to do this. 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've spend many minutes and even hours to discover something a code author knew but was too lazy to put into comments. I don't remember a single case when I suffered from an outdated/incorrect comment (though in this discussion such situations are mentioned).
- antihero 5y agoOr to put it more succinctly: Code is the what, comments are the why/why not.
- ryanthedev 5y agoI comment stack overflow links when using some random code I copied.
- spcebar 5y ago/* * DO NOT EDIT THIS CODE YOU MORON. * THESE AREN'T THE LINES YOU'RE LOOKING FOR. * MOVE ALONG. *
- gen220 5y agoantirez (creator of redis) has some good thoughts on this topic, that people here might find valuable: http://antirez.com/news/124 http://antirez.com/news/124