[HN Gopher] Writing Well-Documented Code - Learn from Examples
       ___________________________________________________________________
        
       Writing Well-Documented Code - Learn from Examples
        
       Author : ainzzorl
       Score  : 206 points
       Date   : 2021-09-04 16:07 UTC (6 hours ago)
        
 (HTM) web link (codecatalog.org)
 (TXT) w3m dump (codecatalog.org)
        
       | achenatx wrote:
       | some types of comments are redundant.
       | 
       | These days I write my code as comments first and then write the
       | code.
       | 
       | But for example this one                       // If either token
       | bucket capacity or refill time is 0, disable limiting.
       | if size == 0 || complete_refill_time_ms == 0 {
       | return None;             }
       | 
       | The comment is the same as the code. It is pointless. Instead I
       | might say under what circumstances I expect them to be zero or
       | why Im disabling limiting when they are zero.
       | 
       | This one is great, though at first glance I cant relate the
       | actual code to the comment, at least I understand why the code is
       | there.                           // We still have burst budget
       | for *some* of the tokens requests.                 // The tokens
       | left unfulfilled will be consumed from current `self.budget`.
       | tokens -= self.one_time_burst;
       | self.one_time_burst = 0;
        
         | Zababa wrote:
         | I don't think the comment is the same as the code. If "size"
         | was called "token_bucket_capacity" I would agree but since it's
         | not, if you remove the comment you lose some context.
        
         | Koshkin wrote:
         | > _understand why the code is there_
         | 
         | You hit the nail on the head here. This is the single most
         | important reason for having comments in code (aside from just
         | being a part of a coding standard).
        
         | komon wrote:
         | In defense of the first comment, when first approaching a body
         | of code like this, it's not always going to be clear what
         | returning None is going to mean in any given method.
         | 
         | Also, one thing I think doesn't get mentioned enough is the use
         | of comments as anchors for text search. Having "disable
         | limiting" expressed in English that way makes it easier for
         | newcomers to explore the codebase.
        
           | kyleee wrote:
           | Good point. Also the phrases in the initial comment "token
           | bucket capacity" and "refill time" may serve as hints and can
           | be used as entry points to searching external documentation.
        
             | codethief wrote:
             | I agree, though I think it would be even better if
             | variables were named "token bucket capacity" and "refill
             | time" in the first place.
        
           | [deleted]
        
           | bcyn wrote:
           | It's hard to judge out of context. IMO None meaning "disable
           | limiting" should be a docstring/comment at the method level,
           | describing what its return values mean, not inline next to
           | this code.
        
         | [deleted]
        
       | makeitdouble wrote:
       | More and more I feel these huge comment blocks with the following
       | inline comments sprinkled everywhere should really be a separate
       | documentation file with its own structure where anyone not
       | familiar enough can get up to speed, and understand the core
       | principles behind the code written here.
       | 
       | For instance in the firecracker example, they don't write 3 pages
       | of block comments to explain the token bucket algorithm (or do
       | they?), as anyone could go read the wikipedia article instead.
       | 
       | Comments living with the code have their benefits, but here I
       | can't imagine these huge comment blocks or algorithm related
       | warnings get revised anytime outside of project wide refactoring.
       | 
       | What we also miss by having these comments inlined is the higher
       | perspective of how it works with the other classes or how it fits
       | in their running context. Anything that spans multiple class
       | and/or methods makes it difficult to decide where to put the info
       | and what scope it should have. People usually end up explaining
       | the same things at 3 or 4 places in sublty different ways, which
       | makes no one happy.
        
       | 29athrowaway wrote:
       | Well documented code is respectful of the maintainer's time.
       | Nobody wants to read a monologue full of noise to understand what
       | is happening.
       | 
       | Comments are not monologues. Explain what the line you are
       | commenting does, and perhaps elaborate why. But always
       | acknoweledge: more words = more patience required = more
       | maintenance cost.
       | 
       | Also, nobody will care about what your name is in 2 years. Do not
       | make the code about you.
        
         | Zababa wrote:
         | On the other hand, if something is missing in the comments, it
         | could take days to find out exactly what you need. Maybe a
         | "level of comments" like log levels could help here?
        
           | willseth wrote:
           | Making it easy to hide comments == making it easy to forget
           | to update comments.
        
             | Zababa wrote:
             | That's a good point. Maybe add a check if the function
             | changed and the comment didn't to remind people? But
             | comment are already easy to forget to update, as they are
             | not code.
        
       | ChrisMarshallNY wrote:
       | I find that doing a "headerdoc" kind of thing works for me.
       | 
       | I did write up a thing about it, but it's a long read, so folks
       | don't usually read it:
       | https://littlegreenviper.com/miscellany/leaving-a-legacy/
       | 
       | Has some pretty heavy-duty examples.
        
       | codethief wrote:
       | Speaking of source code comments, antirez (of Redis fame) wrote a
       | fantastic article[0] about that topic some time ago and I still
       | recommend it to colleagues whenever they make the hollow
       | statement that "code should and can be intelligible on its own,
       | without any comments".
       | 
       | [0]:
       | https://web.archive.org/web/20210226004600/http://antirez.co...
       | (I still don't understand why he deleted his blog)
        
         | audit wrote:
         | Thank you for this link. I appreciated antirez's
         | categorization: " During my research I identified nine types of
         | comments:
         | 
         | - * Function comments - * Design comments - * Why comments - *
         | Teacher comments - * Checklist comments - * Guide comments - *
         | Trivial comments - * Debt comments - * Backup comments
         | 
         | "
         | 
         | I tend to write 'debate comments' of the software that I write
         | for my own business (sole proprietor). I think they fit the
         | 'why' category above.
         | 
         | I often doubt my own decision making process, so I tend to
         | write it out in comments, so that I can I can see reasoning.
         | 
         | My general challenge with comments is of 'maintanence'. The
         | tools to maintain comments, cross link them across diagrams or
         | other hand-written documents -- are hard to find.
         | 
         | So am gradually switching to my own directive that 'all
         | documents about implementation, the API and their usage, are to
         | be generated from my comments'.
         | 
         | Again, not a lot of tools that I found in this area, but at
         | least it is possible to write my own tools (using IDE APIs) in
         | this area.
        
         | PebblesRox wrote:
         | I love this line: "Comments are rubber duck debugging on
         | steroids, except you are not talking with a rubber duck, but
         | with the future reader of the code, which is more intimidating
         | than a rubber duck, and can use Twitter."
        
         | cpach wrote:
         | Huh? That URL is still alive: http://antirez.com/news/124
        
           | codethief wrote:
           | Huh? I've been getting
           | 
           | > Sorry, I can't find that page :-/
           | 
           | for several months
        
             | ReactiveJelly wrote:
             | Works with pure HTTP. Try it in curl? Also see my sister
             | comment for elaboration
        
           | ReactiveJelly wrote:
           | Maybe it's a buggy HTTPS redirect in GP's browser? Due to
           | HSTS or something?
           | 
           | The HTTP version of your URL works fine. The HTTPS version
           | has an expired cert. If I click past that, it redirects to
           | redis.io, then gives a 404.
           | 
           | I know antirez is a smart guy, but if this is some kind of
           | "I'm taking a bold stance against HTTPS" then I'd rather read
           | the archive.org link with functioning HTTPS. My threat model
           | prefers trusting archive.org to correctly reproduce the blog,
           | over trusting everyone between me and antirez.com.
        
             | kyleee wrote:
             | Let's hear more about your threat model that causes you to
             | wory about nefarious content being injected into a blog
             | post about comments in code
        
               | Gh0stRAT wrote:
               | Not OP, but residential ISPs were caught injecting ads
               | into HTTP sites at least as early as 2014. [0]
               | 
               | I certainly wouldn't trust Comcast to keep malicious ads
               | out of their ad network, either.
               | 
               | [0] https://www.techdirt.com/articles/20140908/0719122845
               | 3/comca...
        
               | sinsterizme wrote:
               | How about not opening the gates for third parties to
               | inject ads, trackers and crypto miners
        
               | brazzledazzle wrote:
               | A bit snarky but I agree, it doesn't seem like a huge
               | threat. I'd love to be proven wrong though.
        
               | cpach wrote:
               | I agree that in this case (reading an article) HTTP is
               | not a huge threat. But in 2021 I consider HTTPS + HSTS to
               | be a basic hygiene factor.
        
             | codethief wrote:
             | Wow, you just opened my eyes - I really thought he had
             | deleted his blog! Must be the HTTPS Everywhere extension
             | I'm using - though I really don't understand why it
             | redirects me to redis.io just because antirez's TLS
             | certificate is for redis.io, not antirez.com. I would
             | really prefer a clear error message here.
        
               | cpach wrote:
               | The web server(s) at antirez.com are weirdly configured.
               | So it's not so easy for the web browser to display a very
               | clear error message in this case.
               | 
               | If you run this command you can see a little more clearly
               | what's going on:                 wget --no-check-
               | certificate -S -O - https://antirez.com/news/124
               | 
               | If you use the plain HTTP URL, everything works fine.
               | 
               | If you try https://antirez.com/news/124 the web server at
               | antirez.com:443 will answer this:
               | HTTP/1.1 301 Moved Permanently       Server: nginx/1.10.2
               | Date: Sat, 04 Sep 2021 18:15:46 GMT       Content-Type:
               | text/html       Content-Length: 185       Connection:
               | keep-alive       Location: https://redis.io/news/124
               | 
               | So it's not HTTPS Everywhere that redirects, it's the web
               | server itself.
               | 
               | However, many clients won't heed this response, since
               | antirez.com:443 serves a certificate that's not valid for
               | that hostname.
        
               | cratermoon wrote:
               | Looks like the cert is for a different domain (redis.io)
               | _AND_ it expired August 7, 2020.
        
         | abootstrapper wrote:
         | I agree with you. Code should be intelligible on its own
         | without comments. It should also be well documented. One does
         | not preclude the other.
        
           | codethief wrote:
           | I'm not sure we agree. But I guess the question comes down to
           | what you and I mean by "intelligible".
           | 
           | antirez provides several examples where the code _without_
           | the comments would be much harder to understand and /or
           | maintain. Whenever this is the case, I would argue that
           | comments are a _must_ and without them the code is at least
           | _barely_ intelligible.
        
           | cratermoon wrote:
           | I've forgotten who first wrote this, so I can't credit them,
           | but there's a saying that if someone can't write clear,
           | clean, and understandable _code_ , why does anyone expect
           | them to be able to write clear, clean, and understandable
           | English (or whatever language)?
           | 
           | It's quite a bit easier to write something the compiler or
           | runtime can understand, there's no need for meaningful names,
           | consistent structure, or conceptual coherence. As long as it
           | builds and passes whatever tests, the computer will accept
           | it.
        
             | nicoburns wrote:
             | > if someone can't write clear, clean, and understandable
             | code, why does anyone expect them to be able to write
             | clear, clean, and understandable English
             | 
             | Isn't the answer to that obvious? The code is significantly
             | constrained in form by having to be executable. The
             | comments have no such restriction.
        
             | codethief wrote:
             | While surely not the source of the saying, antirez argues
             | in a similar direction:
             | 
             | > You may think that writing comments is a lesser noble
             | form of work. After all you _can code_! However consider
             | this: code is a set of statement and function calls, or
             | whatever your programming paradigm is. Sometimes such
             | statements do not make much sense, honestly, if the code is
             | not good. Comments require always to have some design
             | process ongoing, and to understand the code you are writing
             | in a deeper sense. On top of that, in order to write good
             | comments, you have to develop your writing skills. The same
             | writing skills will assist you writing emails,
             | documentation, design documents, blog posts, and commit
             | messages.
             | 
             | In any case, you're making a good point, though I would
             | argue that the reverse of the saying (with the modification
             | that "expectations" get replaced with "trust") also holds:
             | 
             | If someone is not able to write intelligible, stringent
             | English, I wouldn't trust them to write good code, either,
             | because writing good code requires similar qualities (good
             | stringent structure, empathizing with the future reader of
             | your code etc.) and, as antirez argues convincingly, it
             | also requires writing comments (which are in plain
             | English).
        
             | unchar1 wrote:
             | I first heard that in a talk by Kevlin Henney [1]. I'm not
             | sure if he's the one who came up with it though.
             | 
             | [1]:
             | https://twitter.com/KevlinHenney/status/381021802941906944
        
             | einpoklum wrote:
             | > if someone can't write clear, clean, and understandable
             | code, why does anyone expect them to be able to write
             | clear, clean, and understandable English (or whatever
             | language)?
             | 
             | The comments don't say the same thing as the code. In the
             | comments, the author might tell us - albeit not clearly or
             | in proper English, what they want to achieve, or why
             | they're doing it this way.
        
           | Koshkin wrote:
           | Very often it is just not possible to _truly_ understand code
           | without comments (or other form of documentation). This
           | becomes obvious if you realize that code by itself can only
           | tell you _what_ is being done, but not _why_.
        
       | namelosw wrote:
       | There are too many comments in there.
       | 
       | Comments are not the first tool people should try to reach
       | because:
       | 
       | 1. That's a lazy way to make the code clear, most code should be
       | self-descriptive. If the teams are spamming comments it's likely
       | to be a bad code base already.
       | 
       | 2. There's no guarantee the comment is compatible with the code:
       | It's natural language and there's no obvious way to test that.
       | After versions of modification, the comments might still look
       | like they make sense but that's not how the code work anymore.
       | 
       | Two alternatives:
       | 
       | 1. Declarative programming: Try to leverage declarative
       | programming styles more. For example, top-down style dynamic
       | programming or memoization is always more readable and less
       | error-prone than the bottom-up ones. You don't have to fully
       | adopt functional programming or logic programming, but do take
       | some inspiration from them.
       | 
       | 2. Testing. Tests are like comments, they reflect some meaning of
       | the code. Tests are not like comments, if the code breaks, they
       | break.
       | 
       | Of course, comments are very valuable, but it's most valuable
       | when applies in the right spots only.
        
       | blondin wrote:
       | unpopular opinion: type hints are killing python's readability.
       | 
       | python is a very readable language. a feature that drew a large
       | multidisciplinary crowd. type hints meant good but are going to
       | hurt the language. if they haven't done so already.
        
       | invincivlepvt wrote:
       | <a href="https://www.instagram.com/invincivlepvt/">Logo Designing
       | Jalandhar</a>
        
       | invincivlepvt wrote:
       | http://www.uniquethings.in/
        
       | billytetrud wrote:
       | I agree with others, code commentary shouldn't be a novel.
       | Comments should only provide info that the code can't make easy
       | to understand. Why it was done this way, what it's intended to
       | do, complex or nonlinear interactions that aren't clear from the
       | code. But adding things that make reading the code sound more
       | like English isn't helpful, it's extra work and prone to getting
       | out of sync.
        
       | jpswade wrote:
       | The code should explain what it's doing (self documenting code)
       | and tests should explain why it's doing it.
       | 
       | Comments tend to just become a place for misinformation or get
       | disconnected from the actual logic.
       | 
       | Adding more comments sometimes doesn't clarify the situation, it
       | just acts as a second source of truth.
        
         | KronisLV wrote:
         | > The code should explain what it's doing (self documenting
         | code) and tests should explain why it's doing it.
         | 
         | I agree at a surface level, however:                 - this
         | makes us assume that there are tests in the first place       -
         | this makes us assume that someone will read these tests instead
         | of asking the developer       - this makes us assume that these
         | tests will be readable enough on their own to replace free form
         | text       - this makes us assume that these tests will even be
         | able to contain a representation of why the code exists       -
         | personally, i have never seen a test that explains a business
         | requirement with enough context not to miss out on details
         | - i have also never seen code that encapsulates these
         | requirements 1:1, without getting too mixed up in
         | implementation details
         | 
         | I think that code definitely should describe what it's doing,
         | tests should explain how it's doing it as far as possible
         | (though this requires discipline to have loosely coupled and
         | testable code, which isn't always the case) and that there
         | still should be comments that explain the realities of needing
         | technical solutions for people problems and all of the aspects
         | that are carried with this.
         | 
         | Doing anything less feels like giving ourselves constraints
         | that will lead to suboptimal results because the tooling and
         | testing solutions aren't quite there yet. Maybe when frameworks
         | and languages will become more expressive, we'll be able to
         | live without comments. However, that day may not come anytime
         | soon.
         | 
         | Nor will companies be interested in the overhead that writing
         | extensive and good tests entail, nor will they want to wait for
         | their engineers to figure out how to convey everything in
         | computer code, as opposed to just dropping some comments into
         | the codebase, right next to the actual code that they concern.
         | Maybe when companies are ready for 50% of the development time
         | to be spent on testing software, that won't be an issue. That
         | day may also not come anytime soon.
         | 
         | As a possible counterpoint, look at RSpec, i think it's headed
         | in the right direction: https://rspec.info/
        
         | Zababa wrote:
         | > and tests should explain why it's doing it
         | 
         | I was going to say "So for performance "hacks" there should be
         | a clean implementation that's benchmark against the current
         | implementation for example?" as a way to disprove what you
         | said, but while writing it I realized that it may actually be a
         | pretty good idea.
        
           | dmurray wrote:
           | Yes, there should pretty much always be this.
           | 
           | You've just written some messy unclear code for performance
           | reasons, so it deserves more thorough tests than average.
           | 
           | And you've already written the clean version anyway, since
           | you hopefully didn't write the optimized version until after
           | you profiled the slow one. So it's not even significant extra
           | work to turn that into your test suite.
        
             | Zababa wrote:
             | This could also be a great way to check if your optimized
             | version is still necessary with new versions of your
             | language implementation. The more I think about it, the
             | more it seems like a great idea.
        
               | dmurray wrote:
               | I wouldn't generally throw benchmarking into the unit
               | test process, because it can be brittle. What if
               | something else clobbers the CPU on your test machine at
               | just the wrong time. What you really want from your unit
               | tests is for them to run quickly, so you run them as
               | often as possible, and reliably, so any failure means
               | something is wrong. I'd use the slow implementation just
               | for checking correctness.
               | 
               | But separately, if you want to add a performance
               | benchmarking process (great!), you have a reference
               | baseline implementation for free.
        
               | Zababa wrote:
               | Maybe not directly in the unit tests that you always run
               | on your machine, but having them around could be a good
               | idea.
        
       | SergeAx wrote:
       | On my team fit/engineering values interview I always asking about
       | benefits of autotests. People who said that tests written
       | alongside the code are the best documentation are getting a
       | mental "plus one point".
        
       | [deleted]
        
       | Sykander wrote:
       | A lot of this I find to be kinda bad commenting, you've got to
       | remember NOT to just directly comment on what the code is doing,
       | but rather explaining why. With future updates your comments will
       | eventually be wrong if they do anything other than give context.
       | 
       | If all your comment does is say what the code on the next line is
       | doing, don't. Instead just try to make the next line more
       | readable.
        
       | ahallock wrote:
       | I like meta comments about the business or technical decisions
       | behind the code. You can come up with clever method and variable
       | names to help enlighten the reader, but nothing beats an
       | intimate, first-hand account explaining the _why_.
        
       | didip wrote:
       | I have a simple rule to go by. Comments should describe "why" and
       | the code should describe "what".
        
         | SV_BubbleTime wrote:
         | WHY comments drastically improved my code.
         | 
         | I've similarly been paying much more attention to convey INTENT
         | which I think is massively missing from computer science. The
         | code might suck, but if the intent is clearly defined, it helps
         | to refactor later.
        
         | ozim wrote:
         | I agree and first example in the article is all comments
         | describing what the code is doing. There is not a single one
         | explaining why.
         | 
         | Well I stopped reading further.
        
         | trinovantes wrote:
         | "Why not" comments are also very helpful
         | 
         | Self-explanatory code can't explain themselves if they do not
         | exist
        
         | ainzzorl wrote:
         | While I agree with the general sentiment, the first example in
         | the article IMO demonstrates how "what" comments make
         | understanding code easier. When I first read that code, I was
         | pleasantly surprised how easy it was to understand everything
         | going on there, even though I had no familiarity with the code
         | base. This is rare for non-trivial projects. I'm not sure if it
         | could be made as clear without those comments.
        
           | Rapzid wrote:
           | Agree; could be very helpful if somebody not fam with token
           | buckets arrives at this code for some reason and needs to
           | make sense of it. Also, I think one person's "what" is
           | another person's "why":
           | 
           | > if self.one_time_burst > 0 {
           | 
           | What is this code doing? It's setting up a flow control
           | statement. It's dereferencing the "one_time_burst" property
           | on the object self and comparing the value to 0. If the value
           | is greater than 0, it will execute the proceeding code block.
           | 
           | Why is this being done?
           | 
           | > [to] consume the one-time-burst budget.
        
         | ChrisMarshallNY wrote:
         | Agreed.
         | 
         | That's what works for me.
        
         | ridiculous_fish wrote:
         | How do you know what a function does, without a "what" comment
         | to explain it? Even "obvious" functions like Math.max have edge
         | cases, and I rely on "what" comments to understand how those
         | cases are handled.
        
         | einpoklum wrote:
         | I upvoted you, but there are plenty of exceptions. For example:
         | 
         | * Common name of the algorithm you're using
         | 
         | * Reference to somewhere else in the code that's related
         | 
         | * "You may think this code only does X, but it really also does
         | Y"
         | 
         | * "We used to also do XYZ here, but that was removed because of
         | ABC"
         | 
         | and so on.
        
       | jpollock wrote:
       | I had a lot of trouble reading that code. I kept getting
       | distracted by the comments and missed the code. The code seems
       | pretty self-explanatory. I have some changes I would make, but
       | they really depend on performance vs depth (modulo the burst vs
       | budget bug).                 // Hit the bucket bottom, let's
       | auto-replenish and try again.       self.auto_replenish();
       | 
       | Is ugly. Why repeat in English exactly what the code says? I
       | don't even know what language this is, but I know it's
       | replenishing the tokens in the bucket.
       | 
       | All of the comments in reduce are redundant, this is what I would
       | write at the top, so that anyone using the method doesn't have to
       | page through to figure out what it does, it also makes the
       | "smells" more obvious:                 // reduce: attempt to
       | consume tokens from bucket,        // starting with
       | one_time_burst, overflowing to        // budget.        // (keep
       | comment only if _expensive_):Performs       // auto-replenish
       | when       // burst is emptied, and budget has insufficient
       | // tokens.       // Asserts size, but only on replenishment.
       | // On OverConsumption, entire bucket is emptied.        // On
       | Failure, only one_time_burst is emptied.       // In all cases,
       | tokens is reduced by amount        // fulfilled.
       | 
       | I don't understand why OverConsumption is different to Failure.
       | Both will result in throttling by the caller. The reason for the
       | difference should be documented.
       | 
       | I'm also curious why burst is consumed, then budget. I would
       | expect _budget_ to be consumed first (with refill) with overflow
       | into burst? My expectation is for burst and budget to have
       | different refill schedules in auto_replenish, so using burst
       | first would result in more failures by missing refill
       | opportunities.
       | 
       | I'm also curious why the size assertion is only on requests that
       | result in refills. Is it guaranteed that size =
       | max(one_time_burst + budget)? Why care about the difference? Is
       | hogging the tokens "bad"?
       | 
       | Then, I'd work to remove the need for those comments -
       | particularly the need to explain what happens on error - which
       | should be "nothing", or that the bucket is emptied of whatever is
       | available, not something in between.
       | 
       | Finally I'd remove the mutation of tokens, returning either
       | unfulfilled or fulfilled in the return value.
        
       | timdaub wrote:
       | IMO, comments are needed when the code itself can't express
       | something necessary to understand its overall function.
       | 
       | I've found that hence e.g. for rather complex statements where
       | the code isn't lacking information, not commenting is the correct
       | approach.
       | 
       | Whereas sometimes, when I'm forced to write exceptional code
       | because of e.g. a workaround, a comment can nicely introduce my
       | future self and other readers to the context.
        
       | blitz_skull wrote:
       | If you must dump a 5-paragraph essay about why something exists,
       | you put it in the git commit message so when you git blame those
       | lines, you see the history of the code.
       | 
       | These examples are a fucking nightmare.
        
       | bandyaboot wrote:
       | When I see code with a lot of inline comments, I can't help but
       | think that a lot of them would make sense to implement as trace
       | log messages instead. If you're going to write all these messages
       | documenting the flow of the program, why not give yourself the
       | ability to flip a switch and output them somewhere?
        
       | pojzon wrote:
       | IMHO writing a well-documented code requires a discipline and a
       | set of good habbits.
       | 
       | One of those habbits is to update documentation (tests/comments)
       | when software is evolving.
       | 
       | Unfortunately it is a very rare habbit it seems.
        
       | willseth wrote:
       | The Protobuf documentation made me cringe. Every character of its
       | "personality" adds a cognitive burden for the reader and a
       | maintenance burden for anyone who has to update it. If a
       | developer wants to be cute with the same brevity and clarity that
       | the comments would have otherwise, fine. Otherwise it's self-
       | indulgent performative trash that should be rejected in review.
        
         | SV_BubbleTime wrote:
         | Absolutely. That was not a good example for me.
         | 
         | > self-indulgent performative trash
         | 
         | A little harsher than I would have used; but now that you say
         | it.
         | 
         | >that should be rejected in review.
         | 
         | Without question. I would have absolutely denied that until it
         | was trimmed to at most 10% of what was there.
        
       | mibollma wrote:
       | I like the idea of codecatalog. Would be nice to see some
       | functional Kotlin examples that go beyond list processing.
        
         | ainzzorl wrote:
         | Thanks! If you know some good examples, please consider
         | proposing them:
         | https://github.com/ainzzorl/goodcode/issues/new?assignees=&l...
        
       | lifeisstillgood wrote:
       | Time and active readers.
       | 
       | Want well documented (and tested and thought out) code?
       | 
       | Then give the coders people outside of their team / hierarchy who
       | are going to check it / read it / use it.
       | 
       | And then give them time.
       | 
       | And repeat.
        
       | dadlangia4 wrote:
       | Way to much
        
       | MattGaiser wrote:
       | I just prefer nice, long, descriptive function names.
       | 
       | I was working on an unfamiliar codebase yesterday and had to work
       | with the postMessage function. It was React, so one might assume
       | that it sends the message to the backend, which was my initial
       | assumption. Nope. It posted it to the page. Didn't help that
       | another utility had another postMessage that was about what to do
       | after the message was sent.
        
         | SavantIdiot wrote:
         | I worked with a guy who wrote a CPU simulator and exceeded the
         | MSVC 256-char function name limit. It's hard when you like
         | 80/100 col code and a function name is longer than that.
        
           | rightbyte wrote:
           | Does escape new line work in function names in C? Brb.
           | 
           | Edit: Hah. It does.
        
         | tartoran wrote:
         | Better than writing really long descriptive function names is
         | to not get carried away but write well described function names
         | that show some intent or description and are chosen carefully.
         | I worked on some code bases using long descriptive function
         | names (inherited from another dev) and it wasn't always useful.
         | It was overkill. The descriptions were either too generic, too
         | descriptive (redundant in half the cases) or handling such long
         | saussage names was simply tiring. When you have to scroll right
         | to read a name it becomes a problem..
         | 
         | The takeway is that merely writing very long descriptive names
         | isn't a silver bullet and could cause harm despite good
         | intentions.
         | 
         | I suggest going back a after a few days for a refactoring
         | (renaming functions or variables) and see how it reads to you.
         | Then repeat the process a few days later when you're even more
         | detached from that code.
         | 
         | In many cases self documenting code is going to help you
         | remember the model you had in your head when building it. And
         | if done well it will help others as well, your code will end up
         | not giving headaches to future maintainers.
        
           | SV_BubbleTime wrote:
           | x100 on intent!
           | 
           | Even something simple like "if the function starts with "is"
           | it will return a Boolean has helped me organize things that
           | return status codes and have side effects. Small thing, but I
           | like it.
        
       | jmartrican wrote:
       | I have seen two extremes on this over the years... comment a lot,
       | or do not comment at all. In the teams I work in, I would love to
       | see a more moderate and practical view on the matter.
       | 
       | I get the whole document with your code, and practice that. But
       | sometimes we end up with variable names that get very long and
       | start leading not the most aesthetic code that gets formatted in
       | a very vertical way.
       | 
       | Don't know the right answer, but suspect the two extreme views
       | are not correct.
        
       | rgoulter wrote:
       | Worth comparing: http://steve-
       | yegge.blogspot.com/2008/02/portrait-of-n00b.htm... A "n00b" is
       | scared of code, and wants as much help to understand it as
       | possible. An "expert" already knows all they need to know to work
       | on the code, and is more productive by putting as much code on
       | the screen as they can.
       | 
       | Rather.. I think part of the point is, context matters. If the
       | team is small, and the project is changing rapidly.. I think the
       | needs and expectations for documentation are different than if
       | the project or team is large and change is slow.
        
         | codethief wrote:
         | > an "expert"
         | 
         | Here's the problem: "Experts" (or "veterans" as the author
         | calls them) are not created equal: There's the expert that
         | already knows the code because she's worked on it countless
         | times and already has a very detailed mental model of the code
         | and there's the expert who's a very experienced programmer but
         | has never seen the code before.
         | 
         | Even experts of the latter category appreciate good comments
         | when they read code (surely not comments of the "n00b" kind
         | portrayed in the article but comments nonetheless).
        
       | vinaygaba wrote:
       | I have a really similar motivation behind a project that aims to
       | teach Jetpack Compose in the same fashion and funny enough, the
       | name is also pretty similar to the title of this thread - Learn
       | Jetpack Compose By Example. You can find it here -
       | https://github.com/vinaygaba/Learn-Jetpack-Compose-By-Exampl...
       | 
       | There's a ton of comments in every example (even though they
       | might be redundant across the examples) and the idea is that you
       | should be able to learn this new framework by merely reading
       | through the examples.
        
       | seanwilson wrote:
       | For the first example with conditions, I much prefer rolling the
       | "why" of the comments into boolean variable names where possible
       | e.g.                  // We still have burst budget for *all*
       | tokens requests.        if self.one_time_burst >= tokens {
       | ...        } else {           // We still have burst budget for
       | *some* of the tokens requests.
       | 
       | becomes something like (I'm missing context but you get the
       | idea):                  enoughBudgetForAllTokenRequests =
       | self.one_time_burst >= tokens             if
       | enoughBudgetForAllTokenRequests           ...        else
       | ...
       | 
       | I don't see this often though. I see the commenting pattern a lot
       | where the comment usually duplicates the "what" of the
       | conditional code, and it's often ambiguous if the comment is
       | talking about the condition or a whole branch.
       | 
       | I think a descriptive variable makes the code easier to skim,
       | it's more precise and less likely to become inaccurate. For a big
       | complex conditional, you can break in up into several well-named
       | boolean variables you compose together (but obviously comment the
       | bits that can't be covered by a concise variable name).
        
         | samsquire wrote:
         | Long variable names mean you perceive your simple code as being
         | too complicated. It's an if statement. I would refactor your
         | long variable name to something more compact like
         | enough_budget.
        
           | [deleted]
        
           | [deleted]
        
       | Fire-Dragon-DoL wrote:
       | The first has an enormous amount of visual noise and it's
       | definitely over commented.
       | 
       | The second one is ok, but please don't follow the first one as a
       | good example, it takes away the ability to scan the code
        
         | ainzzorl wrote:
         | I agree that some comments in the first example are
         | unnecessary, e.g. the one pointed out in [0], but I find
         | comments like that at worst useless, but not harmful. They have
         | a potential to become harmful if someone updates the code but
         | doesn't bother to update the comment, but I can't see how it
         | takes away the ability to scan the code.
         | 
         | [0]: https://news.ycombinator.com/item?id=28416777
        
           | Lio wrote:
           | It's tricky, I think I remember reading a paper by Microsoft
           | research (I'm really sorry; looking for a source) that showed
           | a correlation between bugs and _all_ lines of code including
           | comments.
           | 
           | So if that's true redundant comments do hurt you.
           | 
           | Anecdotally in dynamic languages incorrect comments related
           | to types seem to be a constant pain for me. They're
           | unverified and so a second source of truth that often wrong
           | and can't be trusted.
        
             | Rapzid wrote:
             | > correlation
             | 
             | > So if that's true redundant comments do hurt you
             | 
             | Anyway, even if there was causation proven it might need to
             | be weighed against other priorities.
        
         | codethief wrote:
         | > The second one is ok, but please don't follow the first one
         | as a good example, it takes away the ability to scan the code.
         | 
         | IMO if at all, this type of comment ("Why was X designed this
         | way") should go to the very bottom of the file (maybe with a
         | very short comment at the top of the file referencing it), so
         | it doesn't bother anyone who works on the code on a regular
         | basis. And one could (should) also decrease its verbosity.
         | 
         | EDIT: Confused first and second example
        
           | ainzzorl wrote:
           | A lot of code files starts with lengthy copyright notices,
           | and no one seems to mind. I find comments at the top very
           | easy to ignore if I work on that code regularly. Also, I
           | don't think I've ever seen comments at the bottom of a file!
           | 
           | I wonder if Protobuf wasn't open-sourced by Google, that
           | comment would've been replaced with a link to a design doc.
           | Google docs weren't a thing in early 2000s when Protobuf was
           | originally written though.
        
             | codethief wrote:
             | > A lot of code files starts with lengthy copyright
             | notices, and no one seems to mind.
             | 
             | Hmm, maybe I'm the odd one out but I actually find them
             | quite annoying if they're longer than just a few lines.
             | 
             | In any case: People often just scroll past and ignore
             | lengthy comments at the top (maybe precisely because
             | they're used to copyright notices), so I think a short
             | comment at the top like "For design considerations and
             | reasons this code has been written the way it is, see the
             | very bottom of this file" will attract much more attention.
             | 
             | > Also, I don't think I've ever seen comments at the bottom
             | of a file!
             | 
             | True, but how often do you see code comments about design
             | considerations in the first place?
        
         | nerdponx wrote:
         | The "first things first" comment was bad, but I'd rather have
         | it + the other comments than have none of them.
        
       | pcmoney wrote:
       | Personally I found most of those examples to be not great. I
       | think they would be improved better names overall, more well
       | named private methods and most importantly well structured
       | companion test classes proving the behavior.
       | 
       | I really dont want to read another developers comments on their
       | mental state while I am feverishly debugging their code during a
       | 3am page.
       | 
       | The number of times I have been misled by an outdated comment. I
       | generally open git blame to see if the comments predate any code
       | now. Tests on the other hand almost never lie.
       | 
       | Readmes or comments explaining why something exists vs what it
       | allegedly does are generally much better. If you can't write
       | expressive code why would you assume your English is much better?
        
         | mrathi12 wrote:
         | Agreed, I think that the code itself should be readable through
         | better names, with the comments being a bonus rather than
         | critical to the understanding of the code.
        
         | tempest_ wrote:
         | That is how I feel about these comments.
         | 
         | In a vacuum I like them and when I bump into a piece of 10 year
         | old code commented like this it is great.
         | 
         | There is one caveat however, they have to be meticulously
         | maintained and always updated to reflect every change made to
         | the code. It is a huge caveat because more often than not the
         | comments are out dated and no longer reflect the actual code
         | and at that point they are detrimental.
        
           | coliveira wrote:
           | That's why Knuth had the idea of creating literate programs
           | where documentation and code was maintained in a single
           | block. Unfortunately, this idea was never used in large
           | scale.
        
         | AlexCoventry wrote:
         | > If you can't write expressive code why would you assume your
         | English is much better?
         | 
         | Because English is optimized for communicating human intent?
        
         | omegalulw wrote:
         | Yup, the rate limiter comments are unhelpful. A top level
         | comment explaining the idea is fine (and very useful) but code
         | should largely be self documenting.
        
         | nijave wrote:
         | >The number of times I have been misled by an outdated comment
         | 
         | Imo a problem with code review and not leaving comments. Just
         | like tests need changed during refactoring, documentation and
         | comments should also be cleaned up as part of the change
         | 
         | I have found those as well but place the blame on the person
         | who made the subsequent change and ignored them
        
           | prpl wrote:
           | There's not many code review platforms that are great at
           | showing you relevant comments in a diff because they are
           | often in a much different part of the file, so I kind of
           | think it's hopeless in a large code base to catch this sort
           | of thing in a code review
        
           | oxfeed65261 wrote:
           | ...and on the reviewer(s) who accepted the code change even
           | though the comments no longer match the code.
        
         | t-3 wrote:
         | Exactly. In my opinion, Thinking Forth by Leo Brodie should be
         | required reading for anyone who touches code.
        
       | crateless wrote:
       | I wish there was an option for dark mode or something.
        
       ___________________________________________________________________
       (page generated 2021-09-04 23:00 UTC)