• jonathanvmv8f@lemm.ee
    link
    fedilink
    arrow-up
    9
    ·
    edit-2
    1 hour ago

    Asking as a newbie programmer: how do you suggest we write comments that explain the ‘why’ part of the code? I understand writing comments explaining the ‘what’ part makes them redundant, but I feel like writing it the former way isn’t adding much help either. I mean, if I created code for a clock, is writing “It helps tell what time it is” better than writing “It is a clock” ?

    It would really help if someone could give a code snippet that clearly demonstrates how commenting the ‘correct’ way is clearly better than the way we are used to.

    • flashgnash@lemm.ee
      link
      fedilink
      arrow-up
      4
      ·
      edit-2
      25 minutes ago

      “tells the user the current time” would be an excellent comment for a clock

      I’m not the best at commenting my code, but generally I just try to think of what information I’d want to know if looking at this 10 years from now

      Imo comments are best used sparingly, don’t bother commenting something that anyone with a basic understanding of programming would understand straight away by reading the code

      Functions should generally be commented with what parameters are and what they’re for, plus what they output

      use reqwest::Client;
      
      // create a http client class that all other files can import 
      // so as to only create one instance globally 
      
      pub struct HttpClient {
          client: Client,
      
      }
      impl HttpClient {
              pub fn new() -> Self {
                  HttpClient {
                      client: Client::new(),
                  }
              }
      
              pub fn client(&self) -> &Client {
                  &self.client
      
              }
      
      }
      

      Here’s an example where if I were to stumble onto this file 10 years from now, I might think wtf is this looking at it out of context, the comment explains why it exists and what it’s used for

      (we’ll ignore the fact I totally didn’t just add this comment because I suck at commenting personal projects)

    • jbrains@sh.itjust.works
      link
      fedilink
      arrow-up
      3
      ·
      31 minutes ago

      Write comments that explain why the code isn’t obvious just by reading it. Why did you do things the long way? What did you need to work around? Why didn’t you do the thing that anyone reading the code would expect you to do?

      Also write comments that explain the purpose of the functions you use, in case the names of those functions don’t make it clear on their own.

    • marlowe221@lemmy.world
      link
      fedilink
      English
      arrow-up
      4
      ·
      41 minutes ago

      “Why” comments make more sense as application complexity grows.

      You also have to consider interaction of the code with other external systems - sometimes external APIs force you to write code in ways you might not otherwise and it’s good to leave a trail for others on your team (and your future self…) about what was going on there.

      • jonathanvmv8f@lemm.ee
        link
        fedilink
        arrow-up
        1
        ·
        28 minutes ago

        I believe you confused the ‘how’ of commenting the ‘why’ with ‘why’ of commenting the ‘why’, if that makes sense.

        I am already aware of and totally agree with the need to document your code in this fashion for the convenience of others and self. What I am troubled about is its implementation in real life. How does one write comment that explains the ‘why’ of the code? How would I know if I haven’t accidentally written something that explains the ‘what’ instead or anything that is simply redundant? It seems like this portion is left out ‘as an exercise for the reader’.

        • marlowe221@lemmy.world
          link
          fedilink
          English
          arrow-up
          1
          ·
          9 minutes ago

          I think that, in many cases, “what” and “why” are very similar to each other or are closely related.

          I’ve had an experience like this on more than one occasion - I come into an established code base for the first time. I’m working on a new feature/refactor/bug fix. I am reading through a function that is relevant to me, scratching my head a bit, and thinking “I think I see what this function is doing, but why did they do it such a screwy way?” Often there are no comments to give me any clues.

          In the past, I have foolishly changed the code, thinking that I knew better… But what often happens is that I soon discover why my predecessor did something that looked so weird to me. They weren’t stupid - there was a reason for it! And then I end up putting it back…

          Point being, in a situation like that the “what” and the “why” are going to have a lot of overlap. So, personally, I try to write comments that highlight assumptions that won’t be obvious from reading the code, external constraints that matter but don’t actually show up in the code, and so on.

          I am far from perfect at it and I probably don’t write enough comments. But when I do, I try to write comments that will be reminders to myself, or fill in gaps in context for some hypothetical new person. I try to avoid comments that literally explain the code unless it’s particularly (and unavoidably) complex.

      • something_random_tho@lemmy.world
        link
        fedilink
        arrow-up
        1
        ·
        38 minutes ago

        100%. I also like to leave comments on bug fixes. Generally the more difficult the fix was to find, the longer the comment. On a couple gnarly ones we have multiple paragraphs of explanation for a single line of code.

    • Dunstabzugshaubitze@feddit.org
      link
      fedilink
      arrow-up
      4
      ·
      42 minutes ago

      the “what” is interesting on interfaces or when you generate documentation with some tool like sphinx or javadoc.

      the “why” is interesting when you are somewhere inside a class or function and do something in a “strange” way, to work around a quirk in the codebase or something like that, or when you employ optimizations that make the code harder to read or atleast less obvious why somethings are done.

    • QuazarOmega@lemy.lol
      link
      fedilink
      English
      arrow-up
      2
      ·
      edit-2
      28 minutes ago

      Making up an example on the spot is kinda difficult for me, but I’d look at it this way with a bold statement, you should hope that most code won’t need comments. Let’s exclude documentation blocks that are super ok to be redundant as they should give a nice, consistent, human readable definition of what x thing does (function, constant, enum, etc.) and maybe even how to use it if it’s non-intuitive or there are some quirks with it.
      After that, you delve in the actual meat of the code, there are ways to make it more self explanatory like extracting blocks of stuff into functions, even when you don’t think it’ll be used again, to be used with care though, as not to make a million useless functions, better is to structure your code so that an API is put into place, enabling you to write code that naturally comes out high level enough to be understood just by reading, this thing is very difficult for me to pinpoint though, because we think of high level code as abstractions, something that turns the code you write from describing the what rather than the how, but really, it’s a matter of scope, a print statement is high level if the task is to print, but if the task is to render a terminal interface then the print becomes low level, opposite is also true, if you go down and your task is to put a character onto stdout, then the assembly code you’d write might be high level. What I mean to say is that, once you have defined the scope, then you can decide what level of knowledge to expect of the reader when looking at your code, from there, if some process feels fairly convoluted, but it doesn’t make sense to build an abstraction over it, then it is a good place to put a comment explaining why you did that, and, if it’s not really clear, even what that whole block does

      • jonathanvmv8f@lemm.ee
        link
        fedilink
        arrow-up
        2
        ·
        15 minutes ago

        Interesting to see your opinion on how commenting shouldn’t be mandatory. I specifically go the extra mile to ensure my code is readable for everyone, by naming my variables and functions to be as self-explanatory as possible and breaking down long expressions to store chunks in variables. This is why I was feeling confused as to what more I could add to explain my code better, though I must admit there are still considerable complex portions in some of my projects that would appreciate similar simplification.

  • lnxtx@feddit.nl
    link
    fedilink
    English
    arrow-up
    9
    ·
    2 hours ago

    Self-explainable, when you aren’t writing spaghetti Perl scripts.

  • stupidcasey@lemmy.world
    link
    fedilink
    arrow-up
    2
    ·
    2 hours ago

    It should have the numbers change in the middle like a digital clock but look like the numbers on a clock.