• philm@programming.dev
      link
      fedilink
      arrow-up
      54
      arrow-down
      42
      ·
      11 months ago

      Yeah, but unironic…

      If your code needs comments, it’s either because it’s unnecessarily complex/convoluted, or because there’s more thought in it (e.g. complex mathematic operations, or edge-cases etc.). Comments just often don’t age well IME, and when people are “forced” to read the (hopefully readable) code, they will more likely understand what is really happening, and the relevant design decisions.

      Good video I really recommend: https://www.youtube.com/watch?v=Bf7vDBBOBUA

      • Pickle_Jr@lemmy.dbzer0.com
        link
        fedilink
        arrow-up
        53
        ·
        11 months ago

        Yeah, another way I’ve heard it phrased is comments are for explaining why you did things a certain way, not for explaining what it’s doing.

        • heikomat@lemmy.world
          link
          fedilink
          arrow-up
          16
          ·
          edit-2
          11 months ago

          Exactly that! Everyone can See “what” is happening, the code is right there. But the code usually doesn’t tell you “why” that is happening - good comments help understand the authors intent and give context, so you don’t have to guess.

          Good comments should explain the things that are not obvious.

          Good comments more than once prevented me from accidentially undoing a fix.

          • nilloc@discuss.tchncs.de
            link
            fedilink
            English
            arrow-up
            2
            ·
            edit-2
            11 months ago

            Yup my comments are generally along the lines of:

            • I could have done this X way, but it ran slower
            • I was running out of time so this it’s mostly copied from (stack overflow url)
            • refactor when time allows

            This is a side effect of doing lots of tiny websites , microcontroller code and mini web apps for under budgeted marketing projects with constantly changing designs and requirements that don’t need to last too long.

      • floofloof@lemmy.ca
        link
        fedilink
        English
        arrow-up
        37
        arrow-down
        2
        ·
        edit-2
        11 months ago

        If you’re working with others, even simple code benefits from comments explaining what it’s intended to do. Sure you can read code and get a good idea of what it seems to do, but you can’t be sure that’s what it was meant to do, or why it was meant to do that. Having a quick statement from the author enables you to work faster. And if you find a mismatch between the comment and the code, it’s a smell that could mean a bug.

        And for methods and functions it’s particularly helpful to have a description at the top. Many IDEs will pop this up when you’re using the method, so you can quickly confirm that it’s appropriate for your needs and get your arguments in the right order.

        I even comment code for myself because it will save me time when I return to the project months later.

        No comments would be fine if you could trust that everyone writes code that does what it’s intended to do and you can read code as quickly as you can read English. Maybe I’m a poor coder but I find neither of these is usually true.

        • philm@programming.dev
          link
          fedilink
          arrow-up
          10
          ·
          11 months ago

          Don’t get me wrong comments != documentation (e.g. doc-comments above function/method).

          I probably was a bit unprecise, as others here summed up well, it’s the why that should be commented.

      • potustheplant@feddit.nl
        link
        fedilink
        arrow-up
        35
        arrow-down
        5
        ·
        11 months ago

        That’s like saying a book’s synopsis shouldn’t exist because you can just read the whole book. Sometimes comments can save you a lot of time and point you in the right direction.

        • BaardFigur@lemmy.world
          link
          fedilink
          arrow-up
          10
          ·
          11 months ago

          Comments also helps explaining why certain non-obvious decisions are made. E.g. a workaround for a bug in a library

        • philm@programming.dev
          link
          fedilink
          arrow-up
          4
          arrow-down
          2
          ·
          11 months ago

          Nah, it’s not, code is modular (IME should be kinda tree-structured), a book is linear.

          So the API should be in your analogy the synopsis. And I haven’t said, that there shouldn’t be any comments. E.g. doc-comments above functions, explaining the use-cases and showing examples are good practice.

          • potustheplant@feddit.nl
            link
            fedilink
            arrow-up
            1
            ·
            11 months ago

            Books can be modular as well (ever heard of “Rayuela” by Cortazar?) But that’s beside the point. The analogy is fine and it works.

      • astraeus@programming.dev
        link
        fedilink
        arrow-up
        18
        arrow-down
        1
        ·
        edit-2
        11 months ago

        This mindset is good, but unfortunately enforces bad programmers to leave their undocumented code in critical places where someone eventually has to figure out what the hell they were doing or refactor the whole damn thing because they got promoted to middle-management and can’t remember why they even wrote it.

          • heikomat@lemmy.world
            link
            fedilink
            arrow-up
            6
            arrow-down
            1
            ·
            11 months ago

            If the comments tell you “what” happens, then yes, they can geht outdated fast. The details of how something works can change quickly.

            But comments documenting “why” something is done (a certain way) - explaining the intent - are probably valid for mich longer.

            In the best case comments aren’t viewed as something that is seperate from the code, but part of it. So that if someone changes the code, the comments has to be checked aswell (if the explanation of “why” something is done actually changed).

      • DaleGribble88@programming.dev
        link
        fedilink
        English
        arrow-up
        18
        arrow-down
        2
        ·
        edit-2
        11 months ago

        I have such a love-hate relationship with that video. On the whole, I think that video is bad and should be taken down. The creator is arguing against a very specific type of commenting but is harassing comments in all forms. It even addresses as such with a 20 second blurb 2/3 of the way into video distinguishing between “documentation comments” - but doesn’t really provide any examples of what a good documentation comment is. Just a blurred mention of “something something Java Doc something something better code leads to better documentation” but doesn’t elaborate why.
        It’s a very devious problem in that I don’t feel like any particular claim in the video is wrong, but taken within the context of the average viewer, (I teach intro. comp. sci courses and students LOVE to send this video and similar articles to me for why they shouldn’t have to comment their spaghettified monstrosities), and the inconsistent use of comments vs. code duplication vs. documentation, the video seems problematic if not half-baked.
        In fairness, it is great advice for someone who has been working in the industry for 15 years and still applies for junior positions within the same company - but I can’t imagine that was the target audience for this video. In my experience, anyone who has been programming on a large-ish project for more than 6 months can reach the same conclusions as this video.

      • SokathHisEyesOpen@lemmy.ml
        link
        fedilink
        English
        arrow-up
        15
        arrow-down
        1
        ·
        11 months ago

        Code comments are useful for browsing a script and understanding it at a glance. I shouldn’t have to scroll up and down across 700 lines of code to figure out what’s happening. It’s especially useful with intellisense, since I can just hover over a function and get a tooltip showing the comment, explaining what it does. It also helps when using functions imported from other files, since it’ll populate the comment showing me what parameters are needed and what each should be. Comments save time, and time is valuable.

      • magic_lobster_party@kbin.social
        link
        fedilink
        arrow-up
        12
        arrow-down
        1
        ·
        edit-2
        11 months ago

        I’ve seen code that look like this:

        int delay = 15 * 60; // 10 minutes

        Even if the comment was on the same line someone forgot to update it. People just ignore comments.

        Better solution is to write (in C#):

        TimeSpan delay = TimeSpan.FromMinutes(15)

        Much more obvious what the code actually means.

        • 18107@aussie.zone
          link
          fedilink
          arrow-up
          8
          arrow-down
          1
          ·
          11 months ago

          A better comment would be delay in seconds as that is the one thing not obvious from glancing at the code.

          • magic_lobster_party@kbin.social
            link
            fedilink
            arrow-up
            13
            ·
            11 months ago

            Or just name the variable delaySeconds if you really want to store it as an int. Bonus is that every use of the variable perfectly communicates what it is.

        • CCatMan@lemmy.one
          link
          fedilink
          arrow-up
          1
          ·
          11 months ago

          Is the better way is a runtime performance hit. Does the compiler optimize this?

          • magic_lobster_party@kbin.social
            link
            fedilink
            arrow-up
            1
            ·
            11 months ago

            It’s probably a little bit slower, but there are other things more worth to optimize than to shave off a few microseconds from a 15 minute delay.

            • CCatMan@lemmy.one
              link
              fedilink
              arrow-up
              1
              ·
              11 months ago

              Yeah, it adds up eventually when working with embedded platforms, but for PC stuff I agree.

      • Awkwardparticle@programming.dev
        link
        fedilink
        arrow-up
        6
        ·
        11 months ago

        One day you will inherit a code base so bad that you’ll end up commenting old code just to make sense of it for yourself because nobody in the company has touched in a couple years and the last people that did no longer work there. It will be dangerously coupled, if you make the right change somewhere it will break everything else. It will be true spaghetti code where you spend 30 min just following a code path to figure out what and why an input into a function needs to be what it is to able to come out of another function in an exact format for anything to work.

        Your so called comment standards and principals are fine if you are building something from the ground up, but the other 95% of the time, you do what you gotta do because your were blessed with a turd that is impossible to polish.

        • philm@programming.dev
          link
          fedilink
          arrow-up
          1
          arrow-down
          1
          ·
          11 months ago

          One day you will inherit a code base so bad that you’ll end up commenting old code

          Will not be the case, I won’t take a job, where I have this situation (or I’ll quit pretty quickly)…

          Yeah my “comment standards” (btw. as others mentioned here, I was unprecise/unlucky with the choice of words, I meant “comment the why” or doc-comments totally fine and should be aimed)

          Your so called comment standards and principals are fine if you are building something from the ground up

          Yes that was also targeted with my comment. But what you’re referring to is just missing documentation, and I think this should be done on a higher level. The “comment why” rule applies for spaghetti code non-the-less…

      • Vilian@lemmy.ca
        link
        fedilink
        arrow-up
        5
        ·
        edit-2
        11 months ago

        and if you need an unnecessarily complex code for performance sake?

        • hstde@feddit.de
          link
          fedilink
          arrow-up
          14
          ·
          11 months ago

          There’s a comment for you to explain the why.

          Rule of thumb: code explains the how and what, comments explain the why.

        • magic_lobster_party@kbin.social
          link
          fedilink
          arrow-up
          5
          ·
          11 months ago

          Those cases are rare. Often the most basic solution is good enough.

          If you have to write complex code, then you should write a comment (write the name of the algorithm for example).

      • Cows Look Like Maps@sh.itjust.worksOP
        link
        fedilink
        arrow-up
        3
        ·
        edit-2
        11 months ago

        Or you’re stuck within the confines of a horrible legacy system which the business will not allow you the time to refactor/rewrite but still want your code to be somewhat readable.

        But in general, I agree with your argument. When writing from scratch or improving reasonably well designed code, often documentation could be replaced by breaking it up into another function or naming variable better. It’s a bit of a code smell for violating the SRP. And yet there are times that documentation is needed for the “why”. Things are nuanced I guess.

    • nexussapphire@lemm.ee
      link
      fedilink
      English
      arrow-up
      9
      ·
      11 months ago

      I’ll be that person who makes an catch block for something as simple as double n = 2+5.

  • onestop@lemmy.ml
    link
    fedilink
    arrow-up
    44
    ·
    11 months ago

    code: return isPersonAStudent()

    manager in code review: WHY NO DOCUMENTATION!!??

  • EnderMB@lemmy.world
    link
    fedilink
    arrow-up
    28
    ·
    11 months ago

    Comments don’t describe the code. They describe the decision to use this business logic.

    If you stick to good engineering practices, like small methods/functions, decoupling, and having testable code, you don’t often need many comments to show what your code does. I always recommend a method signature, though, because you can save a few seconds by just saying that a block of code does, rather than me needing to read exactly how you turned one dict into another dict…

    • MrSqueezles@lemm.ee
      link
      fedilink
      arrow-up
      6
      ·
      11 months ago

      I agree for inline code comments, like, “# Save the sprocket”, right above the line that saves the sprocket. Does this include documentation? Because when I see a prepareForSave function that references 10 other functions and I just want to know, “Is this mutating and how is it preparing for save and when should I call it?”, having the author spend 15 seconds telling me is less time consuming than me spending 5 minutes reading code to find out. Anyone who has read API docs has benefited from documentation.

      • EnderMB@lemmy.world
        link
        fedilink
        arrow-up
        3
        ·
        11 months ago

        No, commenting a function should be commonplace, if not only so that your IDE/editor can use the documentation when the signature is found elsewhere in your code.

        Within a function, though, basically means that something gnarly is happening that wouldn’t be obvious, or that the function is doing more than it (probably) should.

  • Alien Nathan Edward@lemm.ee
    link
    fedilink
    arrow-up
    21
    ·
    edit-2
    11 months ago

    `//Get CustomerInfo from CustomerRepository by Customer ID or else throw an CustomerNotFoundException

    public CustomerInfo getById(String customerId) {

    return customerRepository.getById(customerId).orElseThrow(new CustomerNotFoundException());
    

    }`

    This is the kind of pointless comment I see in my codebase all the time. Best I can tell, a couple of my coworkers like to plan out their code using comments, then backfill in the actual executable code. That’s fine, but they leave the comments in when they add no value.

    ` public static LocalDate parseEndDateFromString(String dateString) {

        try {
    
            String[] split = dateString.split("-");
    
            //In order to get the last day of the desired month, we go to the first day of the next month, account for rollover, then subtract one day
    
            int month = Integer.parseInt(split[0]) == 12 ? 1 : Integer.parseInt(split[0]) + 1;
    
            return LocalDate.of(Integer.parseInt(split[1]), month, 1).minusDays(1);
    
        } catch (Exception e) {
    
            throw new RuntimeException("Invalid date format - must be MM-YYYY");
    
        }
    
    }`
    

    Stuff like this, otoh, is where comments are useful. The required format is obvious from the error message, the param and return from the method signature, the only part that requires a comment is the fiddly logic of accounting for the edge case where month == 12 and the rationale behind how we determine the last day of the month. As a rule, comments are for why something is being done, if it’s not obvious, and for magic numbers. Code should tell you what code does.

    edit: can anyone spot the bug that I introduced with that parseEndDateFromString() method?

  • spudwart@spudwart.com
    link
    fedilink
    English
    arrow-up
    21
    arrow-down
    1
    ·
    11 months ago

    Make it deceptively easy to read.

    It appears easy to read in a review of the code, but upon any further glance, to actually keep it up, the only one who can understand it is you.

  • Smoogs@lemmy.world
    link
    fedilink
    arrow-up
    14
    arrow-down
    1
    ·
    11 months ago

    Wow the comments here sounds like you’re all a bunch of antisocial nightmares to deal with in rL.

      • gornius@lemmy.world
        link
        fedilink
        arrow-up
        9
        arrow-down
        1
        ·
        11 months ago

        General rule of thumb: Comments say why is it here, not what it does. Code itself should describe what it does.

    • Sylvartas@lemmy.world
      link
      fedilink
      arrow-up
      10
      ·
      11 months ago

      But then you write code in the real world and find out that you have to write some ass backwards code every other day because of deadlines, backwards compatibility or whatever, and suddenly you realize that despite your best efforts, code cannot always be self documenting.

      Source: me.

      • Sylvartas@lemmy.world
        link
        fedilink
        arrow-up
        1
        ·
        11 months ago

        In a vacuum, sure. On a real project of substantial size with more than one programmer, I’m afraid it’s a “cannot”

    • BaardFigur@lemmy.world
      link
      fedilink
      arrow-up
      23
      ·
      edit-2
      11 months ago

      Comment smart, don’t comment every line like this

      int i = 5; // Assigns the value 5 into the variable i.

      • Maalus@lemmy.world
        link
        fedilink
        arrow-up
        5
        ·
        11 months ago

        Comment only in extraordinary situations, when something you read can confuse someone. And by that I mean the business logic, not that you used a method that’s confusing to people since they only know the basics of the language.

        • Sylvartas@lemmy.world
          link
          fedilink
          arrow-up
          2
          ·
          edit-2
          11 months ago

          Honestly, after a few years of working with juniors (and being one myself before that), I have to disagree with the last part. Sure, it’s fine for solo projects but people’s programming skills can vary heavily. I know people who will pull the wildest C++ compile time tricks you’ve ever seen, but a pointer to a pointer would somehow break their brain.

      • stebo02@sopuli.xyz
        link
        fedilink
        arrow-up
        1
        ·
        11 months ago

        I usually comment on whole groups of lines of code, so the goal of each part of the code is clear

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

      I would disagree. I love to use comments to format my code and separate the sections. I think it’s so beautiful. Also I love when libraries have ASCII art in the comments at the top of the main file lol. It makes the code more fun in my opinion.

      I went to college with a guy who would treat the code as art when presenting projects. His code was always beautiful. Not super functional but always beautiful. It always stuck with me. I want my code to always be functional and beautiful. Easy to read and a pleasure to work with. That’s my goal at least. Comments help with that.

      Also it depends on what the code is for haha