• JasonDJ@lemmy.zip
    link
    fedilink
    arrow-up
    86
    arrow-down
    1
    ·
    3 months ago

    My comments are just the code that didn’t work but I don’t want to delete yet because I might make it work except I never will be cause I already rewrote it so it does.

  • object [Object]@lemmy.blahaj.zone
    link
    fedilink
    arrow-up
    53
    ·
    edit-2
    3 months ago

    Hey thanks for reminding me I made a clock squared in blender about 2 years ago

    yes there is an error in the image, and no I’m not telling you where it is

    • cmhe@lemmy.world
      link
      fedilink
      arrow-up
      5
      ·
      3 months ago

      An interesting concept would be if all hand on the 12 clocks would work, but the hands of the clock in the middle are stuck at 12 position, this way the hands in the middle would point to the clock showing the correct time.

    • flora_explora@beehaw.org
      link
      fedilink
      arrow-up
      2
      ·
      edit-2
      3 months ago

      What a fun idea!

      Is it on purpose that all clocks in this are coupled at the 3 o’clock position? I assume all the clocks go the same speed. Then the large clock and all the smaller clocks at the 3 o’clock position (there are 13 of them) would show the same time. E.g. in one hour, the 12 o’clock position would show 1 o’clock, but the large clock and all the clocks on the 3 o’clock position would show 4 o’clock.

      Oh and why is it a clock squared if you have three layers of clocks? Isn’t it cubed then?

      • object [Object]@lemmy.blahaj.zone
        link
        fedilink
        arrow-up
        1
        ·
        3 months ago

        I was mainly thinking of making some recursion hence why all the subclocks mirror the parent clock (for that given hour). Also I called it clock squared because I didn’t think the resolution would be high enough for people to actually notice the 3rd level of clocks.

        You might notice that some dials don’t really align with the hours they’re supposed to show. That’s because I had to place a bunch of clocks at varying hours with a viewport rendering the parent clock at an angle that probably made it difficult to spot the errors. I rendered it once and didn’t bother re-rendering it once I saw the errors :)

        • flora_explora@beehaw.org
          link
          fedilink
          arrow-up
          2
          ·
          3 months ago

          Haha yes, recursion is always fun!

          Although I’m still confused on what the clock would show in an hour. Because if the subclocks mirror the parent clock at the given time, then they would all be stuck to the hour they are positioned on? Or if they can move then the sublcocks are coupled to 3 o’clock of the main clock. But well, it is all hypothetical anyways :D

    • darkpanda@lemmy.ca
      link
      fedilink
      arrow-up
      25
      arrow-down
      1
      ·
      3 months ago

      The code directly below:

      function getPathToUploadDirectory() {
        return config.tmp_path
      }
      
    • Omgpwnies@lemmy.world
      link
      fedilink
      English
      arrow-up
      1
      ·
      3 months ago

      If your company uses some sort of code checking tool on PRs, there may be a requirement that all functions have a docstring, even if it’s obvious what it’s doing. Leads to silly comments like this quite often

  • jonathanvmv8f@lemm.ee
    link
    fedilink
    arrow-up
    21
    ·
    edit-2
    3 months 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.

    • pixelscript@lemm.ee
      link
      fedilink
      English
      arrow-up
      20
      ·
      edit-2
      3 months ago

      I recognize three kinds of comments that have different purposes.

      The first kind are doc block comments. These are the ones that appear above functions, classes, class properties, methods. They usually have a distinct syntax with tags, like:

      /*
       * A one-line description of this function's job.
       *
       * Extra details that get more specific about how to use this function correctly, if needed.
       *
       * @param {Type} param1
       * @param {Type} param2
       * returns {Type}
       */
      function aFunctionThatDoesAThing(param1, param2) {
          // ...
      }
      

      The primary thing this is used for is automatic documentation generators. You run a program that scans your codebase, looks for these special comments, and automatically builds a set of documentation that you could, say, publish directly to a website. IDEs can also use them for tooltip popups. Generally, you want to write these like the reader won’t have the actual code to read. Because they might not!

      The second kind is standalone comments. They take up one or more lines all to themselves. I look at these like warning signs. When there’s something about the upcoming chunk of code that doesn’t tell the whole story obviously by itself. Perhaps something like:

      /* The following code is written in a weird way on purpose.
      I tried doing <obvious way>, but it causes a weird bug.
      Please do not refactor it, it will break. */
      

      Sometimes it’s tempting to use a standalone comment to explain what dense, hard-to-read code is doing. But ideally, you’d want to shunt it off to a function named what it does instead, with a descriptive doc comment if you can’t cram it all into a short name. Alternatively, rewrite the code to be less confusing. If you literally need the chunk of code to be in its confusing form, because a less confusing way doesn’t exist or doesn’t work, then this kind of comment explaining why is warranted.

      The last kind are inline comments. More or less the same use case as above, the only difference being they appear on the same line as code, usually at the very end of the line:

      dozen = 12 + 1; // one extra for the baker!
      

      In my opinion, these comments have the least reason to exist. Needing one tends to be a signal of a code smell, where the real answer is just rewriting the code to be clearer. They’re also a bit harder to spot, being shoved at the ends of lines. Especially true if you don’t enforce maximum line length rules in your codebase. But that’s mostly personal preference.

      There’s technically a fourth kind of comment: commented-out code. Where you select a chunk of code and convert it to a comment to “soft-delete” it, just in case you may want it later. I highly recommend against this. This is what version control software like Git is for. If you need it again, just roll back to it. Don’t leave it to rot in your codebase taking up space in your editor and being an eyesore.

    • flashgnash@lemm.ee
      link
      fedilink
      arrow-up
      15
      arrow-down
      1
      ·
      edit-2
      3 months 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
      11
      ·
      3 months 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.

    • Dunstabzugshaubitze@feddit.org
      link
      fedilink
      arrow-up
      10
      ·
      3 months 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.

    • marlowe221@lemmy.world
      link
      fedilink
      English
      arrow-up
      8
      ·
      3 months 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.

      • something_random_tho@lemmy.world
        link
        fedilink
        arrow-up
        5
        ·
        3 months 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.

      • jonathanvmv8f@lemm.ee
        link
        fedilink
        arrow-up
        1
        arrow-down
        1
        ·
        3 months 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
          5
          ·
          3 months 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.

    • xmunk@sh.itjust.works
      link
      fedilink
      arrow-up
      6
      ·
      3 months ago

      Not everything needs a comment - knowing when comments add value is the key… “what” vs “why” is usually a good indicator but some code just doesn’t need a comment.

      • darklamer@lemmy.dbzer0.com
        link
        fedilink
        arrow-up
        3
        ·
        3 months ago

        Doesn’t need any comment:

        int getCount() { return count; }

        Absolutely needs a very extensive comment:

        double getBojangleFlux { return fubar * .42; }

    • MotoAsh@lemmy.world
      link
      fedilink
      arrow-up
      5
      ·
      edit-2
      3 months ago

      IMO, the most important parts are to document the actual intent of the code. The contract of what is being documented. Sure, it’s only so useful in perfectly written code, but NO code is perfect, and few will come through later with full context already learned.

      It makes it sooo mich easier to know what is intended behavior and what is an unchecked edge case or an unexpected problem. If it’s a complicated thing with a lot of fallout, good documentation can save hours of manually lining up consequences and checking through them for sanity.

      You might say, “but that’s indication of bad code!”. No. Not really. Consequences easily extend past immediate code doing things as trivial as saving data to the database without filtering, or having a publicly available service. Even perfectly coded things come up with vulnerabilities all the time due to underlying security issues. It’s always great to have an immediate confirmation of what’s supposed to happen whether it’s immediate code or some library with a new quirk in a new version.

    • Ethan@programming.dev
      link
      fedilink
      English
      arrow-up
      4
      ·
      3 months ago

      My comment game has gotten far better since I started doing live code reviews. Essentially I ask myself, “Would I feel the need to explain this to someone during a code review?” and if the answer is yes I add a comment.

    • Presi300@lemmy.world
      link
      fedilink
      English
      arrow-up
      4
      ·
      3 months ago

      What I usually do is I explain what the function does and, if not self explanatory, explain why it does such thing. Like, with the clock example, I’d explain that it tells the time and then, if not immediately obvious, explain why the time needs to be known… Smth like that.

      There is no “correct” way of commenting code. I personally think the more verbose, the better, but that’s an unpopular opinion afaik. As long as the code can be understood, the comment is doing it’s job.

      PS, I’m also kinda new to programming, mostly doing JS and React stuff

      spoiler

      I love putting memes in comments :P

    • QuazarOmega@lemy.lol
      link
      fedilink
      English
      arrow-up
      3
      ·
      edit-2
      3 months 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
        1
        ·
        3 months 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.

        • QuazarOmega@lemy.lol
          link
          fedilink
          English
          arrow-up
          3
          ·
          3 months ago

          Yes, I feel like some kind of bell should ring in your brain when something needs to be commented, most often if you struggled to write out the solution or you had to do a lot of digging from various places to achieve the final resulting piece of code, it doesn’t make a lot of sense to pressure yourself into thinking you should comment everything, because some knowledge has to be assumed, nowadays you could even add that if someone completely extraneous to the codebase entered without any knowledge, they could feed the parts of code they need to understand into some LLM to get a feel for what they’re looking at, with further feedback from actual devs though, you never know what random bs they might write.
          Good one on the variables to store results of expressions, I agree with that method, though I always forget to do that because I get so lost in the pride of writing that convoluted one-liner that I think, “oh yeah, this is perfectly beautiful and understandable 😇”, I have to check myself more on that.

          complex portions in some of my projects that would appreciate similar simplification

          So I’m not alone on that haha.

          This is why […] better

          Sorry, what’s the subject of that?

          • flashgnash@lemm.ee
            link
            fedilink
            arrow-up
            3
            ·
            3 months ago

            This is unfortunate for new programmers cause I think it’s some kind of learned instinct rather than a hard rule

          • jonathanvmv8f@lemm.ee
            link
            fedilink
            arrow-up
            2
            ·
            edit-2
            3 months ago

            This is why […] better

            Sorry, what’s the subject of that?

            I was just referring to my original question i.e. how I should write comments in my code to explain its working if I have already done so in the code itself

    • zeekaran@sopuli.xyz
      link
      fedilink
      English
      arrow-up
      1
      arrow-down
      2
      ·
      3 months ago

      Unless you’re writing something in the open source world, rarely does any code need comments at all.

      • Ethan@programming.dev
        link
        fedilink
        English
        arrow-up
        5
        ·
        3 months ago

        That’s a hot take. If you want your code to be maintainable at all, it needs comments. If you’re part of a team, write comments for them. If someone else may take over your project after you move on, leave comments for them. And have you ever tried to read uncommented code you wrote a year ago? Leave comments for yourself.

    • Swedneck@discuss.tchncs.de
      link
      fedilink
      arrow-up
      16
      ·
      edit-2
      3 months ago

      //forgive my sins, it took me 2 hours to nail down this arcane spell. if anyone touches this they will know my wrath
      =(/&)((//((%=)(&)%)(&()

  • GooberEar@lemmy.wtf
    link
    fedilink
    English
    arrow-up
    12
    arrow-down
    4
    ·
    3 months ago

    I know some folks are joking about and dunking on this, but in modern times, I have justification. Call me lazy, but I have found myself writing out these comments and then letting the AI take over to at least give me a sketch of an implementation. Works reasonably well and saves me a lot of time and effort. Mostly I don’t bother to remove them, though I usually edit them a bit.

    On the other hand, there are factions within my colleagues who steadfastly insist that commenting is unnecessary and to some degree even potentially harmful, and that if you feel the need to comment your code, it means your code should be improved so that it’s obvious what it is doing without the need for comments.

    • theherk@lemmy.world
      link
      fedilink
      arrow-up
      13
      ·
      3 months ago

      And your colleagues are probably correct with respect to this sort of «what it does» commenting. That can be counterproductive because if the code changes and the comment isn’t updated accordingly, it can be ambiguous. Better have the code be the singular source of truth. However, «why it does it» comments are another story and usually accepted by most as helpful.

      • ChickenLadyLovesLife@lemmy.world
        link
        fedilink
        English
        arrow-up
        8
        arrow-down
        2
        ·
        edit-2
        3 months ago

        if the code changes and the comment isn’t updated accordingly, it can be ambiguous.

        People always cite this as a reason comments are bad. In 30+ years as a developer I have seen (and participated in) a lot of failed software projects, but not once has a mismatch between comments and code been the actual cause of the failure. Moreover, the same logic could be applied to the names of methods and variables (“if the code changes and the method and variable names aren’t updated accordingly, it can be ambiguous”) but nobody ever suggests getting rid of that. At the end of the day, comments are useful for imparting information about the code to future developers (or yourself) that is too complicated to be adequately communicated by a method name.

        • theherk@lemmy.world
          link
          fedilink
          arrow-up
          6
          ·
          3 months ago

          I didn’t say the source of failure. I said a source of ambiguity. And having also been in the industry for decades, I have encountered it many times, where a junior programmer or somebody new to a project read some documentation and assumed a behavior which in fact did not match the current implementation. So you may have been fortunate, but your experience is certainly not ubiquitous.

          With respect to variable names, I’d suggest those too should absolutely be updated too if the name is given in a way that adds ambiguity.

          I’m not saying comments are bad; rather that bad comments are bad, and sometimes worse than no comment.

      • Overshoot2648@lemm.ee
        link
        fedilink
        arrow-up
        5
        ·
        edit-2
        3 months ago

        I’ll add that you should have a comment anytime you are using some sort of algorithm to explain what it is and the expected result when it’s not intuitive or a complex math operation that isn’t immediately clear. Ex// I’m using Newton’s Method to approximate a solution to speed up the inverse square root

    • Benjaben@lemmy.world
      link
      fedilink
      arrow-up
      5
      ·
      3 months ago

      Would you mind sharing a bit more about the workflow you’re describing? I’m on a “ask people how they’re using AI to help them dev” kick.

      Sounds like you’re using an agent integrated with your IDE, would you be willing to give specifics? And you’re talking about writing some comments that describe some code you haven’t yet written, letting the AI take a stab at writing the code based on your comments, and then working from there? Did I get that right?

      Happy for literally any elaboration you feel like giving :)

      • GooberEar@lemmy.wtf
        link
        fedilink
        English
        arrow-up
        3
        arrow-down
        1
        ·
        edit-2
        3 months ago

        I use VS Code and GitHub Co-pilot and develop in a variety of different languages and frameworks. I’ve got lots of experience with some, but I’m less knowledgeable on others.

        So, having the AI assist with languages I am very familiar with is basically a way to save time and preserve my mental energy. For languages and frameworks I’m less experienced with, it speeds things up because I’m not having to constantly search how-tos and forums for guidance. And for languages/frameworks I have limited or no experience with, it can be a helpful learning tool that speeds up how long it takes to get ramped up.

        With this set-up, if I start writing a line of code and then pause for a moment, co-pilot kicks in and tries to autocomplete that line, sometimes even suggests the entire block of code. It’s really good at recognizing simple patterns and common boilerplate stuff. It’s less good at figuring out more complex stuff, though.

        However, I find that if I start out by writing a comment that explains what I’m trying to accomplish, and to some degree how to accomplish it before I start writing one of those more complex blocks/lines, the AI has a much higher success rate in returning helpful, functioning code. So, basically yes, I write the comment to describe code I haven’t written, and I’ll let the AI take over from there.

        This works for code, raw database queries, configuration files, and even for writing tests. I’m not an expert at building out Docker configurations for local development or configuring auto-deployment on whatever random system is being used for a project, but I can often get those things up and running just by describing in comments what I need and what I’m trying to accomplish.

        The VS Code co-pilot extension also has some context menu items that let you ask questions and/or ask for suggestions, which comes in handy for some things, but for me, typing out my intentions in comments and then letting the auto-complete kick in as I’m starting a line of code is faster, more efficient, and seems to work better.

        Granted, co-pilot also likes to try to auto-complete comments, so that’s sometimes funny just to read what it “thinks” I’m trying to do. And most of the time, I do remove my comments that were specifically to guide co-pilot on what I wanted it to do if they’re super redundant. And, at the end of the day, not everything co-pilot suggests is production-worthy, functional, nor does what I actually described. In fact, a lot of it is not, so you should expect to go back and fine tune things at a minimum. It’s just that overall, it’s good enough that even with all the supervision and revisions I have to make, it’s still a net positive, for now.

        • Benjaben@lemmy.world
          link
          fedilink
          arrow-up
          1
          ·
          3 months ago

          Awesome, thank you! This largely matches my own experience, I’ve found it (Claude in my case) most useful in areas where I’m weakest. I haven’t tried this scaffolding-via-comments approach though, it sounds cool.

          Any experience with Cursor or other IDEs or agents? Was co-pilot a choice or just kinda a natural default?

    • parpol@programming.dev
      link
      fedilink
      arrow-up
      4
      ·
      edit-2
      3 months ago

      At least docblocking a summary above every method is always good. You can automatically generate documentation this way.

  • linkhidalgogato@lemmy.ml
    link
    fedilink
    arrow-up
    8
    arrow-down
    1
    ·
    3 months ago

    basically how it feel when a professor requires u comment every single line of code u write to explain it. I know people tend to drop out of real engineering to do programing but an entire 4 years of this bullshit as opposed to just a couple classes sounds way worse than calc 3 or differential equations.

    • Urist@lemmy.ml
      link
      fedilink
      English
      arrow-up
      1
      ·
      edit-2
      3 months ago

      The only problem with courses like calc 3 and differential equations (in my experience, as a mathematician) is that they are cheating somewhat. By cheating I mean relying on inadequate, flawed or entirely omitted proofs. How can the students truly understand something if they are not presented the whole story (or at least reference)?

      The good thing about these courses are that there are usually no shortage of relevant exercises!

      • linkhidalgogato@lemmy.ml
        link
        fedilink
        arrow-up
        1
        ·
        3 months ago

        u could be right calc 3 was alright, pretty fun actually but differential equations i still dont get at all, maybe i should try learn it on my own now with more time and no pressure.

        • Urist@lemmy.ml
          link
          fedilink
          English
          arrow-up
          1
          ·
          3 months ago

          I detested differential equations. However, that was more due to how it was presented than the underlying, surprisingly, beautiful math.