[HN Gopher] On Comments in Code ___________________________________________________________________ On Comments in Code Author : nikbackm Score : 80 points Date : 2021-06-15 18:22 UTC (4 hours ago) (HTM) web link (henrikwarne.com) (TXT) w3m dump (henrikwarne.com) | ferdowsi wrote: | Most 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. | d23 wrote: | The 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. | jeddy3 wrote: | Can you explain further what you mean by header-style comments? | | I'm having trouble drawing up a distinct example. | iudqnolq wrote: | Probably // --- Init --- | // --- Mainloop -- // --- Cleanup --- | crazygringo wrote: | Another 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 wrote: | I 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. | simonw wrote: | I love having commentary like that around, but I prefer to keep | it in either the commit message or (more frequently) in the | issue thread linked to from the commit. That way I can use as | much space as I like for it and the timestamps make it clear | that it's historical commentary, not a description of how the | code works right now. | bentcorner wrote: | One caveat with this method is that your source control | system evolves and things get archived. Code is around | forever but everything around it may change. | | 10 or 20 years from now your code may still be running, the | issue system or the git commit log may not be. | Normal_gaussian wrote: | I find an issue link only works if e is a good enough comment | alongside it (ie. Attempting to eliminate this mutex is bug | prone, see <link> for archiyectures and their problems). | neolog wrote: | Some people advocate putting lots of stuff into commit | messages, which makes me think I'm missing something. | | Do you always read the whole git history of a file before | editing it? What interface do you use for that? | ratww wrote: | I also do this with optimisations, when I work on low-level | code: | | If I come up with an inefficient algorithm that's short and | readable, I tend to optimise it to something better but leave | the reference implementation inside a code block. | | (This goes without saying, but: I don't leave "commented code", | but code inside comment, generally formatted with Markdown) | Hasnep wrote: | Is there a reason you don't leave a comment with the commit | hash of the change instead? | Nullabillity wrote: | Sounds like a good use case for property testing! | fouc wrote: | If you have a unit test for that piece of code then that would | probably help to act as a stopgap measure against attempting to | "fix" the complicated-seeming code. | mpoteat wrote: | 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. | | 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 wrote: | nothing 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 wrote: | I 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 wrote: | Depending on the context, I might mention if getFoo is | expansive, is cached, talks to the network, or can throw. | alerighi wrote: | If the name of the function and the parameters are clear, | documenting the code seems useless. | | Take this real example: /** * change | the temperature set point in use by the thermostat * | * @param ctx the thermostat context * @param sp the | new set point in 0.1 celsius degrees * @return 0 on | success, < 0 in case of an error */ int | change_sp(void *ctx, int sp); | | But we can change around the name of the parameters like this | and use proper strict types: /** * | change the temperature set point in use by the thermostat | * * @param thermostat_ctx the thermostat context | * @param set_point the new set point * @return SUCCESS | on success, otherwise an error code */ error_t | update_temperature_set_point(thermostat_ctx_t *thermostat_ctx, | celsius_degree_t set_point); | | And thus the doc comment now it's useless and can be removed, | leaving only: thermostat_error_t | update_temperature_set_point(thermostat_ctx_t \*thermostat_ctx, | celsius_degree_t set_point); | | And in a codebase, more than 95% of the comments would be like | that. There are the exception where you need to explain | something in more details. In that case you first should ask | yourself if there is really not a better way, and if not in | that case the doc comment is fine. In all the other cases, it's | probably not. | | Doc comments on the other hand really makes the code less | readable, the increase the number of lines for most of the | times not saying anything useful at all. | qayxc wrote: | > But we can change around the name of the parameters like | this and use proper strict types | | Sometimes. Other times proper strict types aren't possible | because the language doesn't support them (many scripting | languages, C, etc.) | | Assuming this is C, even a type like "celsius_degree_t" tells | me nothing about the valid range. Am I supposed to just try | it out and see what error code I get or are we back to | looking at the implementation? In the case of C this will | most likely involve locating and opening a completely | different file whose name doesn't even have to be related to | the header file. | | The comment also doesn't need to be about all parameters and | can contain additional information that's non-trivial to | determine: is the function thread-safe, are there performance | implications, is there notable resource usage, and so on. | | Python in particular is notorious for having optional | (keyword-) arguments and polymorphic arguments. Proper naming | schemes are impossible in this case (lest you accept | monstrosities like "node_as_id_or_name_or_object" as proper | argument names) and type annotations have only very recently | (as of 3.10) become somewhat sane. Type annotations don't | help with kwargs, though. | | TL;DR it greatly depends on the programming language and its | capabilities whether naming and types alone can replace | comments. | [deleted] | philosopher1234 wrote: | Why are method names priveleged over comments? They're both | text read for human understanding. Why must the full | documentation/definition for a function fit into the length | of a method? These are silly restrictions, and lead to worse | code. | moeris wrote: | That's more of an argument for them being overused, not for | them being useless. | squiggleblaz wrote: | It's an argument for a certain code style, characterised by | descriptive names and specific types. This calls for a | language capable of e.g. doing maths with user-defined | types, which not all languages can do. | | I think one of the major motivators for the original style | of code are legacy pressures and a concern about code | width. | | If every other function that manipulates temperature set | points takes "int sp", then you're going to get a lot of | pressure for consistency. A lot of programmers regard | consistency as a goal in and of itself, and it's very easy | to demand it during a code review. However, the demand for | consistency prevents us from finding a new consistent | target without excessive amounts of work. It may be better | to reach a new consistency within a narrower scope, as long | as a consensus has been reached to extended that | consistency outwards. In this system, consistency should be | viewed as a compromisable target: something that makes you | ask a careful question. And when asking a question, take | into consideration the propensity of the code author to | view a question as a demand. If you're a senior and the | code author is a junior, presume that means: ask a genuine | question vocally; write down minutes of your discussion. | | The code width concern is a bit silly, but for some reason | we assume that things get weird when lines exceed 80 | characters. That's easy to do. | ericbarrett wrote: | This is maybe OK until you get a library user who doesn't | know what "ctx" means and now you have another Discord ping | or GitHub issue. Just write the documentation. | rav wrote: | Sometimes, 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 wrote: | I 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 wrote: | This 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 wrote: | Exactly my thinking. Very well said. | truetraveller wrote: | This 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. | ElijahLynn wrote: | The 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. | kelnos wrote: | > __most_ of the time_ | | This is the thing that annoys me with arguments about all this. | I will generally say "document the 'why' and not the 'what'; if | the 'what' isn't clear from the code, fix the code to make it | clear". And people will say "that's invalid because sometimes | you really do need to do something clever and the 'what' needs | to be documented" or whatever. And yes, that's fine! Stop | taking everything people say as if it's an absolute, 100%-of- | the-time statement! Obviously there are exceptions. That | doesn't make the common-case rule useless or uninteresting. | People should assume "most of the time" is the default | implication about these sorts of "rules" unless otherwise | noted. | Normal_gaussian wrote: | The funny thing is, when someone writes really 'clever' code, | I need a _why_ more than ever. _Why_ isn 't this simpler? | adonnjohn wrote: | Should my 'why' comment go further than a Jira number? | nonameiguess wrote: | Absolutely. All that information dies when your organization | migrates off of Jira years down the line and the issue ids no | longer exist. | Normal_gaussian wrote: | Absolutely. I worked a codebase that was littered with ticket | numbers for a few years; many members of the team religiously | added them but _never_ read them. How do we know? Self hosted | issue system and access logs. New starts would read a couple | and that was it. | | A ticket is a really opaque way of showing something. If you | click the issue you're now going through several tangentially | related comments and a few MR back and forths just to work | out if its even useful to you. People will stop bothering to | even open the link unless they are really stuck. | | Whack a summary comment and then by all means include the | link, but the comment is what most people will use. | bostonsre wrote: | I wonder if there are jira integrations that would bring | ticket info into the ide. Although, I hate jira and would | definitely prefer good git commits. | jka wrote: | Nicely said. One small adjustment I'd suggest -- because I care | a lot about setting incentives -- is that we generally want not | just _more_ "why" comments, but in particular concise "why" | comments that empathize with and improve the life of future | developers. They're a kind of message-in-a-bottle conversation. | Nicksil wrote: | >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 wrote: | I 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. | firebaze wrote: | To me it's actually faster and easier to read code instead. | This is because i generally don't trust "what" comments - | either I know the code already or I don't, and if I don't, | then I don't trust the "what" comment fully, so I both have | to parse "what" and code. | | A "why" comment usually ages well, so I generally trust it | and can use it to better parse the code and its intentions. | | So I belong in the "what only for API methods" camp. | nicoburns wrote: | Do you also read through every function call (at least | the first time you encounter a given function)? | bostonsre wrote: | I do something like this, but I write them as debug log | statements so that you get the additional benefits from | logging. | isbvhodnvemrwvn wrote: | You might as well be able to extract a method with a | meaningful name then. | nicoburns wrote: | That then makes the code non-linear, which IMO makes it a | lot less readable in most circumstances. | isbvhodnvemrwvn wrote: | It depends, if it needed a comment in the first place it | likely was at a different (likely lower) level of | abstraction than the rest of the code in that method. | nicoburns wrote: | Yes, but that doesn't mean it doesn't benefit from being | inline. I love being able to skim over the paragraph- | comments to get the big picture and then dip into the | details _without_ having to jump to another file / part | of the file and lose my context. | ziml77 wrote: | Please 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. | jbay808 wrote: | What would be your opinion of this comment, though? | // Reset the counter for the next run total_count = 0; | latchkey wrote: | why are you resetting the counter? | dlp211 wrote: | For the next run. Why is in the comment, it's likely a | design flaw though and no comment is going to help here. | See comment about using proper scoping. | rrose wrote: | it feels like this suggests a design flaw. You should | probably be creating a new local `total_count` variable for | each run that goes out of scope at the end of the run, | rather than reusing the same variable over and over again | in different contexts | wongarsu wrote: | // reuse counter for performance, this brings 2% speedup | total_count = 0; | | would be a quite useful why comment, if not creating a | new variable each time is intentional | rrose wrote: | sure, but reusing an integer variable is never going to | bring a 2% speedup. allocating a new variable of almost | any type is not going to cause any performance issues, at | least if it is allocated on the stack, and if the | construction of the variable is particularly expensive, | resetting it probably will be too. | | I would need to see a realistic example to believe that | something like this would ever be a useful comment. | _old_dude_ wrote: | In a compiled language, this is true for a local variable | in general, it costs nothing because the compiler uses a | register for it (or at worst spill it on stack but the | stack frame size is reserved once for all stack allocated | variables when the function is called). | | The story is different, if the variable is captured by a | closure/lambda, the current stack frame or part of it may | be allocated on heap, leading to perf issues. | hnlmorg wrote: | I feel like you're getting bogged down on the literal | code and missing the point of a hypothetical example. | Normal_gaussian wrote: | Ignoring the pedantry elsewhere, then sure this comment | explains what you are doing. | | The contention is whether it is necessary or common enough | to be assumed. In most places this would be self evident | and should be avoided to reduce mental load, however I have | seen and done exactly this many times - in distrubuted or | embedded systems where the control is neither synchronous | or co-located (ie, coming in from interrupts / messages). | In such places there may even be call for more description, | however presuming the context is appropriate this could be | correct. | | I would imagine a game with a react redux style state | engine might result in a comment like this as well. | dcolkitt wrote: | I mostly agree with you, but there are certain cases where | you're making weird and non-intuitive performance optimizations | and have to explain "the what". | aequitas wrote: | But still you have to explain _why_ your code is the way it | is on top of that. You can always deduct the _what_ from | mentally processing the code, but you can 't deduct the _why_ | , you only guess. | ithronmellon wrote: | What belongs in comments describing API methods, why belongs | everywhere else. | pc86 wrote: | If it's impossible to make "what" clear through the code | itself. | iudqnolq wrote: | With a public API it's important to distinguish "currently | true from reading the code" and "promised to stay true | through minor updates". What comments are useful for that | gbear605 wrote: | If a method is part of an API that might be used by | developers external to your team, they don't want to be | looking through your code to figure out how to use your | methods. | CodeMage wrote: | The point on API methods is incredibly important. True, "Why" | is the most important kind of comment, but I disagree with | the author's critique of the documentation-generating | comments and agree with you. | | Yes, "what" comments are a source of additional developer | effort and of possible inconsistencies between code and | comments, but good API documentation is worth writing and | maintaining. | | No matter how well you name your method and its arguments, if | it's part of the public API and you don't include a | comprehensive documentation comment, I'll be forced to dig | through your source. | _bramses wrote: | Wanna jump in here and say I'm working on this exact problem | using GPT-3. The results when added to other dev tools have | been really inspiring, and I'm learning how flexible comments | can be when addressing the "why"[1] instead of just the "how". | | [1]https://replit.com/@bramses/stenography-carbon-bot#index.js | bregma wrote: | I have never cursed an author for having too many comments. There | are many cursed developers out there after my long career. | teknopaul wrote: | You never lived through auto-javadoc? | GuB-42 wrote: | I 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. | da39a3ee wrote: | 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'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/styl... | ridiculous_fish wrote: | I wish for a text editor that shows the comments to the side of | the code, like in a split pane. | ChrisMarshallNY wrote: | Important 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/ | probably_wrong wrote: | I'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. | ozim wrote: | Javadoc comments problem begins as soon what is in javadoc | stops being true. | | So you are usually better of reading the code anyway because | you cannot trust that some dev updating code updated javadoc as | well. | | When something goes wrong I usually have to do is to dig into | GIT history and see when and what changes were connected. | nytgop77 wrote: | Same with naming in code. | | Names do become misleading. Of course making callstack deep | enough, will hide that. | | Code reviews have same power to rectify both: naming and | comment issues. | teknopaul wrote: | Having said that you can spot bad code by its JavaDocs. | | The most reliable Javadoc is @author, git tells you the | author, @author tells you who the code was copy/pasted from. | watwut wrote: | To me the above quote says that author never worked with | anything more complicated or more big then simple crud web app. | ozim wrote: | To me it says that author is perfectly aware that people are | not updating Javadoc comments or normal comments as well. | pjerem wrote: | If 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 wrote: | It 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 wrote: | 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. | redact207 wrote: | The 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. | watwut wrote: | 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. | TrianguloY wrote: | There 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. | slver wrote: | I'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. | chowells wrote: | Sometimes 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/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. | piinbinary wrote: | The 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.ht... | fdr wrote: | 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. | | 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. | aequitas wrote: | 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. | javert wrote: | I 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 wrote: | All code is literature intended exclusively for humans. | Computers read machine instructions; they're incapable of | reading code. Know your audience. | jbay808 wrote: | Humans wouldn't care so much about semicolons, but I do want | the compiler to understand my code, too. | hawski wrote: | Have you seen decompiled code? That's all that compiler | cares about, it is not pretty. | teknopaul wrote: | nonsense. code is intended for a computer by definition. | pjerem wrote: | No. 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. | jaywalk wrote: | Code 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 wrote: | A 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 wrote: | Within 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. | krylon wrote: | I guess that was what I was trying to say. Make your code | as obvious as possible, and use comments to explain | what's not obvious. | | Although people have vastly different ideas of what is or | isn't obvious. | ziml77 wrote: | What's obvious now might not be obvious later or to | another person. | aequitas wrote: | Most 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 wrote: | - 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? | teknopaul wrote: | My golden rule is inline with javadoc being largly useless. | | Don't ever add SBO comments. | | SBO = Stating the Bleeding Obvious. | crazygringo wrote: | > _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 wrote: | The 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. | nytgop77 wrote: | Full 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. | [deleted] | GuB-42 wrote: | Libraries are an exception. Here, from the article, talking | about Javadoc. | | > These comments may be useful for API:s exposed externally, | but in an application where you have access to all the source | code, they are mostly useless. | philosopher1234 wrote: | All code is library code | ravenstine wrote: | When 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. | gield wrote: | To add onto this, the documentation of a method is often a | contract. If the documentation is good, the actual | implementation of the method shouldn't matter to someone only | wanting to use that method. Even moreso, the implementation | could change: maybe there is a more concise or efficient way of | implementing the contract. | jpswade wrote: | Tests should really fill this gap, not comments. | simonw wrote: | I 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 wrote: | Definitely. | | Commit messages are updated with the code automatically. | Comments seem to become out of date almost immediately. | timdaub wrote: | I 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 wrote: | If 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? ___________________________________________________________________ (page generated 2021-06-15 23:00 UTC)