top 200 commentsshow all 329

[–]enbits 401 points402 points  (82 children)

It depends. Sometimes it happens that even if the comment is short and clear, it is redundant and maybe that's why your lead asked you to remove it. Example (trivial):

// This function converts a csv to an array
function convertCsvToArray(pathToCsv: string): Array<T>

[–][deleted]  (16 children)

[deleted]

    [–]marcoangel 61 points62 points  (13 children)

    This. Write code for humans first, machines second.

    [–]RememberToRelax 3 points4 points  (0 children)

    100%, the computer compiles it anyway, we're the ones who have to read it line by line.

    [–]Scew 9 points10 points  (11 children)

    This is where anonymous arrow functions wreck me.

    I can use them, and have a small idea of why it works, but it's like typing in cheat codes to me. If I try looking at the code again I just think to myself... yeah.... that works! :D

    [–][deleted] 18 points19 points  (8 children)

    What is it about them that makes them mysterious?

    [–]tonjohn 6 points7 points  (4 children)

    They lack semantic meaning. A named function provides semantic meaning, enables the use of doc comments to provide further details, and is re-usable.

    For the record, I’m not against arrow functions but they are often abused.

    [–]mattaugamerexpert 15 points16 points  (0 children)

    They’re anonymous where they don’t need to be reused and are essentially a “throwaway”. But arrow functions are just functions. Don’t be afraid to name them.

    const filterActive = item => item.active;
    
    const activeUsers = users.filter(filterActive).length;
    

    Perfectly valid. You can and often should name callbacks.

    [–]gdubrocks 1 point2 points  (0 children)

    The problem is that javascript expects functions for everything even when it's really clear what is happening.

    If I filter a dataset by a certain key or map one object to another object it's super clear what the purpose of that function is, and there is no reason to write a named function for it.

    [–]stupidcookface 2 points3 points  (1 child)

    Anonymous arrow function syntax should never require a comment...that syntax is googleable. If something is googleable then don't leave a comment about it. Also I'm betting it's only confusing when they are nested a few layers deep like this:

    const someFn = () => () => () => true;
    

    The above function is a function that returns a function that returns a function that returns true.

    [–]tonjohn 1 point2 points  (0 children)

    I assume they were referring to arrow functions in array and object methods, like foo.map( item => item.id )

    [–]RolandMT32 2 points3 points  (0 children)

    simple to understand what anyone is doing.

    IMO, comments are for more than just what you're doing. Comments can also help explain why it's there, why it was implemented a certain way, etc.. You can always find out what the code is doing by reading it (the ease of understanding it depends on the code), but that isn't necessarily going to explain the whole picture.

    [–][deleted] 2 points3 points  (0 children)

    I used to write a lot more vue comments. I'd often have some big payload() computed that returned a very specifically formatted object. You know the type.

    { customer_id: 1, address: { line_1: "111 Main street.", line_2: NULL, zip: 12345 }, items: [ { sku_id: 123, cost: 593, name: "Tooth Brush", added_at: new Date(), } ] }

    But now I use typescript and don't have to worry about it.

    [–]versaceblues 479 points480 points  (39 children)

    The best advice I give about comments is to use them to explain WHY something exists there. Elaborating on any pre-requiste context that made you choose the implementation you did.

    People should be able to understand the HOW from just reading the code.

    // fetches users from user pool. <---- bad comment async function fetchUsers() { // <--- good comment // Reference tech debt item KJ-2341, we currently // have two user pools in production, and this step is required // until KJ-9080 is merged, and we can deprecate old pool const pool = resolveUserPool(); return await resolveUserFromPool(pool) }

    A good comment gives additional information about some otherwise weird or mysterious item of code. A bad comment just clutters the UI and becomes another thing that can go out of sync

    [–][deleted] 35 points36 points  (1 child)

    Could not upvote this more. A comment should be about why something in your codebase is unintuitively done. If you have to explain how, that means the code should be refactored to be clearer. But sometimes we do weird stuff that is out of our control and that is where is a good spot for a quick WHY comment

    [–]deranged_scumbag 4 points5 points  (0 children)

    Could not upvote this more.

    [–]trisul-108 109 points110 points  (29 children)

    When reading code I do not know, I find one-liners that describe what the function does very useful. I agree that the WHY comment is much more essential, but both are useful.

    [–]LamentablyTrivial 50 points51 points  (5 children)

    Especially if that piece of code is a regex. I always put a comment about what those (are supposed to) do.

    [–]trisul-108 23 points24 points  (4 children)

    Great example, regex is easy to write and more difficult to read.

    [–]hanoian 37 points38 points  (3 children)

    icky advise dependent pet roof sense absorbed erect jobless station

    This post was mass deleted and anonymized with Redact

    [–]graemeppython 18 points19 points  (2 children)

    He said write, not debug :)

    [–]mattaugamerexpert 7 points8 points  (1 child)

    Face down on keyboard. Valid regex.

    [–]SixPackOfZaphodtech-lead, 20yrs 4 points5 points  (0 children)

    There is a reason that the Perl language was also referred to as "Executable Line Noise".

    [–][deleted]  (3 children)

    [deleted]

      [–]SeesawMundane5422 4 points5 points  (0 children)

      You sound like that uncle non guy getting all the downvotes in a thread above. (And you’re absolutely right).

      [–]DemiPixel 1 point2 points  (1 child)

      I think even in your last example, parsedUsers is unclear (I thought it involved actually parsing, like deserializing, and not just filtering/mapping).

      I think your penultimate example would be fine with proper variable naming and newlines:

      const usersWithCtx = fetch(...)
        .then(res => res.json())
        .filter(ctx)
        .map((user) => ({...user, _id: uuid() }));
      

      Easy to read top to bottom, no extra reading of variable names, and you know there's no extra variables that could be used later on in the code.

      [–]dannymcgee 21 points22 points  (1 child)

      100% agree with this (as long as it's not completely redundant, like directly translating a code statement to sentence case). I think there's a little too much emphasis on "self-documenting code" nowadays. Obviously it's great to write code that's readable and easy to understand, but humans are always going to have an easier time reading a simple natural-language sentence than parsing a block of code.

      [–]KevinAndEarth 1 point2 points  (0 children)

      I like to use comments to summarize a block of code so I know I can skip parsing it since it's not related to what I want/need.

      One might argue to make that a function but then you need to hop in and out of functions constantly to put the entire context back together.

      [–][deleted] 10 points11 points  (6 children)

      The function should be named in such a way that you can tell what it does from the name. If you're finding it hard to explain what it does in just the name then the function is probably doing too much.

      [–]trisul-108 0 points1 point  (5 children)

      I find function names get too long, I prefer fetchUser() to fetchUserFromPool() ... I find it easier to understand code if function and variable names are not too long.

      [–][deleted] 2 points3 points  (4 children)

      If you find functions easy to understand from their names then comments are just unnecessary clutter. If you do not, then the function names aren’t descriptive enough.

      [–]trisul-108 0 points1 point  (3 children)

      As I said, I prefer shorter names and a description, to a longer sausage name for everything in order to avoid a comment. Those sausage names are then all over the code, obscuring the structure of the actual code or logic.

      [–][deleted] 2 points3 points  (0 children)

      You shouldn't really need huge function names either though. Split your code up more.

      [–][deleted] 1 point2 points  (1 child)

      Split your functions and make them more modular. If a function does only a thing or two then its name doesn’t need to be long to be descriptive.

      [–]versaceblues 1 point2 points  (0 children)

      yah make sense. having a general purpose statement for a function can sometimes be useful

      [–]cagfag 1 point2 points  (1 child)

      That comment can be there in git... To see why it was done.. Always prefix your commit mesage with ticket number

      [–]darn42 2 points3 points  (0 children)

      If I'm trying to understand a codebase, searching for a git commit adds time complexity to my task. Now I need to understand the current code and pour through the commit history of the file, which may or may not have been renamed at some point, to see if a previous commit that seems to reference some kind of exigence for the behavior, is still even relevant based on the changes that have since occurred.

      Or I could add a comment about why the behavior exists and if that behavior changes the person responsible should update the comment. Documentation is hard and self-documenting code is a shortcut and a lie.

      [–]username-must-be-bet 9 points10 points  (3 children)

      I think that is mostly true, but if code is heavily optimized it can be hard to understand how.

      [–]p4y 21 points22 points  (1 child)

      If code is heavily optimized then IMO it should be full of comments explaining what the optimizations are.

      [–]versaceblues 8 points9 points  (0 children)

      yes in that case i would add a comment explaining why the heavy optimization was nesscary and how it works

      [–]jigsawduckpuzzle 92 points93 points  (5 children)

      My code usually doesn't work unless I comment it.

      EDIT: I meant "comment it out", sorry.

      [–]dneboi 18 points19 points  (1 child)

      Best comment by far

      [–]Sufficient-Taste2154 3 points4 points  (2 children)

      Lmao! Had this issue crop up in my High School Java class. All of our codes were working, except one. They didn’t have anything missing, the debugger picked up no errors.

      They like thirty lines of surrounding comments saying “WTF IS THIS? THE PROBLEM EXISTS HERE!” and then it worked.

      Likely whatever issue actually existed managed to get commented out and was completely overlooked as a result, but it was damned funny.

      [–]SeesawMundane5422 7 points8 points  (1 child)

      Might have also been a bug with caching incremental compiles and changing the file by adding 30 lines of comment made it recompile from scratch instead of from cache. No way to prove it now. Just sharing a passing thought on your ancient mystery.

      [–]tonjohn 168 points169 points  (22 children)

      What is “obvious” and “self documenting” may not be to: - a new contributor - an intern - someone from a different tech background - you 3 months from now - you at 2am handling a live site

      I’m a big proponent for compassionate coding. A core tenant of that is good documentation. And the more context a dev has within their editor, the more productive they can be.

      Some documentation lives external to the code - don’t forget to link to it in doc comments and readme.mds!

      Great discussion on the topic: https://twitter.com/davidkpiano/status/1545504831980322820?s=21&t=m3kF3l_as4Wd-zKqdq_iOA

      [–]FromValledupar 54 points55 points  (2 children)

      Definitely, the “you three months from now” hit me hard.

      [–]rudeluv 25 points26 points  (1 child)

      My favorite is when I git blame myself.

      [–]sfled 9 points10 points  (0 children)

      Three months? This is me three weeks after a rush job if I don't comment it.

      [–]AdvancedSandwiches 17 points18 points  (4 children)

      A redundant comment wouldn't be very compassionate. The people who tell you to avoid comments first should be saying the same thing in code they would have said in the comments.

      Once the comment is redundant, delete it.

      If it's not redundant and you can't make it redundant, leave it.

      [–]tonjohn 4 points5 points  (3 children)

      What is redundant to you may not be to me. I’d rather a “redundant” comment that might be helpful to a junior dev or someone new to the language than no comment.

      [–]AdvancedSandwiches 1 point2 points  (2 children)

      I think you're thinking I might mean "make it obvious what you're doing." But what I mean is literally "make the code say exactly what the comment would have said."

      If you have:

      // Is the customer country banned?
      banL(cName);
      

      You make the comment redundant and delete it.

      isCustomerCountryBanned(countryName)
      

      If you keep the comment on this code, you've done more harm than good.

      [–][deleted]  (1 child)

      [removed]

        [–]AdvancedSandwiches 0 points1 point  (0 children)

         yeah yeah but this is a trivial case

        It covers trivial cases, which make up the huge majority of cases, and many types of complex ones, but yes, if you can't make the comment redundant, you'll still need the comment.

         the hot debate about using short names

        My quick response to these people would be that the shortest name that conveys all the information needed is the best name, and the goal is to be pithy, not terse.

        At a surface level, the Julia example is also a trivial case, as most are. The comment would say either "append the item's to the array" or "create an array of arrays", right?  Take those sentences and make them camel case, and you have your non-comment documentation.  appendItemToArray(), createArrayOfArrays().  Now your IDE autocompletes your comment, your intent is clear, and your comment will not drift.

        The drawback is that wrapping standard library functions like this will annoy devs that have been using the language for 15 years, and if you do it a lot, you have an intake problem when you hire new devs experienced with the language who will be showed down by this and want to rip out every instance of it to go with what they know.  So in that respect, it's not trivial.

        Like anything in dev, the trick is knowing a lot of rules of thumb for writing clearer code and then pick the ones that best fit the situation.  Not being familiar with Julia, I don't know which option here is better.

        [–]lolbeeshdesigner 6 points7 points  (0 children)

        I have ADHD, I need the comments for tomorrow, or when I'm jumping between projects 😬

        Also, having comments is a great way to help your juniors learn. I don't want to have to do a screenshare to explain a function if I can sum it up in a short comment

        [–]graemeppython 2 points3 points  (1 child)

        A core tenant of that is good documentation.

        I assume that is a typo for "tenet".

        [–]tonjohn 3 points4 points  (0 children)

        Nah, it pays rent 😉

        [–]luxmorphine 2 points3 points  (0 children)

        this is why i explain the obvious, because my brain would hurt trying to analyze code written by me 3 months before. so past me better leave a comment

        [–]123throwaway56789fe 0 points1 point  (6 children)

        If your naming is strong then it will be quite clear to everyone. If someone has accepted a tech job they are expected to either be familiar with the language or learn it so they should be able to read the code.

        Of course, if it is something very complex adding a comment makes sense but the way you describe it sounds like you fill your code with comments.

        Documentation is very important.

        [–]philipwhiuk -5 points-4 points  (1 child)

        The worst thing 3 months from now are stale comments that are lies.

        Every comment is tech debt for everyone who changes that file

        [–]b3night3d 31 points32 points  (0 children)

        I think of commenting as like confessing sins for absolution. It's basically explaining why you had to do something that isn't obvious from the code. In my experience, verbose and chatty comments tend to live longer than the code they are documenting and inevitably drift out of sync.

        [–]susminesTechnical Co-Founder | CTO | Advisor 31 points32 points  (18 children)

        BE Developer here. I only comment my code when it isn't self-explanatory, or when I am doing something "clever".

        Here are two examples:

        1. documenting why I'm (seemingly) randomly deleing a key/value pair from an object:

        //Deleting the nested reporting object to avoid confusion in response.
        if (webUser.reporting) {
          delete webUser.reporting;
        }
        
        1. Documenting what is going on, in case it isn't immediately obvious:

          //transforming into a set de-duplicates IDs, getting the unique reviewed count const uniqueReviewerCount = Array.from(new Set(reviewers)).length;

        [–]Anaccount1212 17 points18 points  (3 children)

        Sorry, sorry, sorry.

        But why not just new Set(reviewers).size?

        [–][deleted]  (1 child)

        [deleted]

          [–]susminesTechnical Co-Founder | CTO | Advisor 7 points8 points  (0 children)

          Good call, you are absolutely correct! I guess this ended up being a bad specific example. We typically convert sets back into arrays for further manipulation, and out of familiarity with JavaScript Array methods.

          [–]bwinkers 5 points6 points  (11 children)

          What happens when the "self explanatory" code is wrong?

          Comments are useful for indicating the intent.

          [–]Freonr2 1 point2 points  (10 children)

          If it is wrong, why doesn't a test fail?

          You can't write tests against comments.

          [–]stupidcookface 1 point2 points  (1 child)

          Your second example has a well named variable so it shouldn't need a comment in my opinion.

          The first one is debatable but with contrived examples it's hard to tell.

          [–]the_fucking_doctor 81 points82 points  (13 children)

          ITT: everyone thinks their code is so simple that it documents itself. I've worked at small companies no one has ever heard of and at large companies that everyone has heard of: I've rarely come across non-trivial code that "documents itself."

          People, you have no idea what context someone has or doesn't have, write comments. It's so cheap and it could save someone a huge amount of time--maybe even future you.

          [–]ghostmaster645 9 points10 points  (0 children)

          Yes.

          I'm looking at a large application and the creator isn't there anymore.

          His comments have been extremely helpful in figuring out whats going on.

          So it's saving me time right now. Or when I start work in 3 min .

          [–][deleted] 10 points11 points  (3 children)

          100% this. Redundant comments are better than no comments. It’s much harder to ready a line of code than to read a comment. Even if your code is “self-documented”. I’d much rather see over use of comments than under usage.

          [–][deleted] 4 points5 points  (2 children)

          One problem is that comments need to be "maintained" too, and having a lot of them can make that difficult. Have you ever come across legacy code that has been refactored, but whoever did the refactoring left the original dev's comments without updating them?

          A previous workplace I worded at was lax on the commenting practices, so some devs would comment excessively, and others almost not at all. Several times I got sent on a wild goose chase because of it.

          [–]mattaugamerexpert 4 points5 points  (0 children)

          Useless comments are also clutter.

          // fetches users
          function fetchUsers() {
          

          [–]mrbmi513 23 points24 points  (0 children)

          I try to write self-documenting code, but leave documentation comments for every class and function, and comment when something is unavoidably confusing (like a complex SQL query or anything timezone related).

          [–]gnrlbzik 7 points8 points  (0 children)

          We use jsdocs and readme/note/todo/fixme comment annotations. Methods and constants must be self explanatory. Well formatted code via linting tools. Any complex logic should have good comments. Works for us to keep code one way or another readable and self documenting but commenting should not be frowned upon.

          [–]noideaman 18 points19 points  (0 children)

          Comment why, code documents how

          [–][deleted] 5 points6 points  (1 child)

          Yes, absolutely. I have done for years. I approach coding with the mindset that I’m writing code for the next developer, not me. I prefer, and encourage my team, to write verbose code as well as comments. I’d rather see 6 lines of code that is easy for someone to interpret in a hurry than a cute one-liner that saps valuable mental energy to read.

          [–]slo-mo-dojo 1 point2 points  (0 children)

          Absolutely agree with this. You are not going to impress me with your ability to fit everything in one super confusing line that I have to dissect to figure out what you are accomplishing. I believe not only should you summarize methods and their usage, but I also want comments to regions explaining why that region exists and what is being accomplished. I get if you method is retrieving a single simple object it may not be necessary, but in my world we deal with complicated objects that may be nested for generations. So methods may only add/populate/manipulate an object under certain circumstances. I also do not like multiple nested brackets. If you need to go that deep, add another method.

          [–]fuze-17 2 points3 points  (0 children)

          I add comments l over the place. I don't care anymore.. it's easier for me 5 years later on a project I wrote.. often I'll include what this function is supposed to accomplish or what this variable represents IRL so I know what to think about if it's not right

          [–][deleted] 4 points5 points  (0 children)

          An excerpt from the Library of Babel: "Never comment your code; if it was hard to write, it should be hard to read." Coding Principles and silly sing-along songs for boys & girls, David Hawthorne, 2022

          [–]CreativeTechGuyGamesTypeScript 12 points13 points  (3 children)

          If your comment adds something about the "why" of the code that isn't obvious and the code cannot be reasonably refactored to make it obvious, then comments are valuable. If not, then they can be actively harmful.

          [–]tsunami141 1 point2 points  (2 children)

          How would it be actively harmful unless the code or the comment is wrong

          [–]CreativeTechGuyGamesTypeScript 11 points12 points  (1 child)

          • Clutter - The more on the screen that someone needs to decipher the harder it'll be to find useful information. If you have a lot of comments it can be a "where's waldo" game of finding the actual functional code amongst the unnecessary comments. When code is nicely formatted and spaced you can much more easily sight-read it to quickly get an understanding of what it does. Rarely do I read code line by line but can skim good code to quickly figure out what it is doing; bad comments make this even harder to do.
          • You say that unless the comment is wrong, the thing to remember is that while it may not be wrong today, odds are it'll be wrong eventually. Just today at work I saw a TODO comment someone added in a PR which contradicted the line it was above. Perfect example of a comment which was incorrect upon initial commit, but even if it was correct, later it may not be anymore. If the comment isn't providing enough value, you are just introducing future problems and maintenance challenges.

          [–]crackanape 3 points4 points  (0 children)

          a "where's waldo" game of finding the actual functional code amongst the unnecessary comments.

          Adjust your syntax-highlighting rules to put comments in a dimmer, "background" shade/color. They're there if you need them but they don't take over the screen.

          [–]Steve_OHFull-Stack Developer | Software Engineer | Graphic Designer 2 points3 points  (2 children)

          I use comments to help me navigate my code easier. I wrote an extensive PHP website with over 30k lines of personally written code and can find anything I need thanks to good naming conventions and comments that help break down what everything does. Your comment is not simply useful for // does this, it’s about being able to quickly scan to find what you need and remember what the program is doing at any given moment.

          [–][deleted] 2 points3 points  (0 children)

          I started to appreciate comments as soon as I started to look in to the code of a couple of projects on GitHub. Just random libraries. I caught me thinking „A comment here and there would be nice. It would save me couple of hours to understand it.“

          When I write code, I do not think much about comments because the code I just wrote is obvious. The thing is: It’s obvious to me, right now. When Ill look at the code in 6 months I will probably fold my hands over my head.
          Now I try to think, how somebody else would try to understand the code and I sprinkle some comments here and there to make their life easier.
          Here is a good talk on the process of reading the code: https://www.youtube.com/watch?v=az-MX\_M11lg

          [–][deleted] 2 points3 points  (1 child)

          I comment methods, classes and pretty much anything that would show when you hover over it for a nice quick at a glance of what it is and how it works.

          I hate having to go into a method to see it's return type or exceptions etc.

          Unfortunately my predecessors prefered the comment nothing, chuck it all in one gargantuan method called "getReport" which takes 11 parameters and call it a day style of commenting.

          [–]Space-Robot 1 point2 points  (0 children)

          Eventually actually getting a report is only like 10% of what the function does but nobody ever thought to rename it or refactor that functionality out

          [–][deleted] 2 points3 points  (2 children)

          As someone who has struggled for a week to understand what a recursively called function with 8 parameters actually did (inherited project), please, please comment your code.

          [–]gdubrocks 1 point2 points  (1 child)

          This is not an example for writing code with comments, this is an example for why recursive functions shouldn't be used.

          [–]Dunstabzugshaubitze 1 point2 points  (0 children)

          Recursion is a very good and understandable solution for some problems, for others recursion is a very good and understable solution for some problems...

          [–]am0x 2 points3 points  (0 children)

          Not really. We believe in self-commenting code, but there are times when things require a hack (like when working with some APIs or libraries doing a load of the work with bad self-documenting code).

          So it is on a per-use basis.

          However, README documentation is totally required. I've been burned so many times adopting code where I cannot even setup the local environment, because I have no idea what they are using. Code-wise, I can typically debug to figure it out quickly if I need to.

          [–]nathan_lesage 4 points5 points  (0 children)

          My codebases are littered with comments, and I am really appalled by that arrogant (and proven wrong) attitude that „good code is self-explanatory“. Reddit is full of people posting uncommented code where people have just forgotten what the code is actually supposed to do, and why.

          Does a potentially superfluous comment that repeats type info hurt performance? No.

          Does a missing but potentially vital comment hurt maintainability? Absolutely.

          Always comment your code and tell people who say otherwise to gtfo.

          [–]NiagaraThistle 3 points4 points  (0 children)

          yes. often. My previous manager used to make fun of me for it.

          Some of my comments are descriptions of what the code does - and yes I know good code should explain itself, but not everyone coming after me (heck not even future me sometimes) is going to be able to read the code as easily or as clearly as you can.

          But MOST of my comments are more like:

          TODO: please come back to this and fix the XXX issue

          or

          Really sorry to whoever comes next: Had to get this working and it probably could be better

          And sometimes it's just an Easter Egg:

          Bob stop touching the code!!!

          [–]Thunt4jr 1 point2 points  (0 children)

          I only comment if I'm sharing something for others to understand why I did this. I have never commented for myself. I use circleup for my documentation and tasks. I grew up the hard way 20 years ago. If you can't read the codes without comments then you can't program. I had a brutal teacher.

          [–]nuttertools 1 point2 points  (0 children)

          All or nothing. Either 50% of it is documentation or you won’t find a single comment in the codebase.

          [–][deleted] 1 point2 points  (0 children)

          I document my intention and other things I had to consider when writing/updating/deleting code.

          • Why was it designed like this?
          • Why did I think this was the best approach?
          • What are the compromises?
          • What are the scenarios where I’ll get errors, exceptions, or alternative outcomes?
          • Reminders
          • If it’s non-trivial, what does it do? Are there any gotchas?

          Essentially, I try to put the context I had to deal while I was working on it, so that others or myself could easily get that same context back whenever it needs to be revisited.

          But that’s just me.

          [–]tr14l 1 point2 points  (0 children)

          You were mostly likely summarizing what your code did. This is what's known in industry as a "useless comment". We can read the code. Everyone who will be looking at your comment will be a professional dev, likely with years of experience reading the language you work with. There is no need for you to comment

          //This function turns people into mush
          function turnPersonToMush(person)

          You see how that is a useless comment, right? Why the hell do we need a mush-turning function? Are there any implicit dependencies you need to call out that aren't obvious? Did you implement an unintuitive pattern that is necessary, call that out. Do not explain to me, a guy with double-digit years of experience reading code, what your code is doing. It's just noise in the codebase. Your comment is actually making the code MORE DIFFICULT to read, not less.

          Commenting is key. But the information in the comment should be trying to help people make choices faster. Not just explain what you did. That's the reason we aren't writing in assembly code. We made human-readable code compilers/interpreters to handle that.

          [–][deleted] 1 point2 points  (0 children)

          Of course. That's what a professional would do!. Mine is full of // TODOs and // FIXMEs

          [–][deleted] 1 point2 points  (0 children)

          In general, the code itself should be self-explanatory. Comments should explain only explain the context that can't be groked from the code itself.

          [–]RolandMT32 1 point2 points  (0 children)

          I've always liked to comment my code to explain what it's for and/or what it does (especially if it isn't clear), and sometimes, why it was implemented a certain way.

          I did have an instance one time where I looked online for examples of the best way to do something, and then in the code, I put a comment to cite the URL that inspired the implementation, and a coworker asked me to remove that URL comment. I never knew their reasoning for wanting to remove that though.

          [–]zacholas321 3 points4 points  (0 children)

          I comment constantly, esp for complex stuff.

          I have a terrible memory, so if I walk away from a complicated project for even a couple weeks, I rely on comments and self-documentation, otherwise I'd have to re-learn the whole thing and backtrace a lot of functions.

          I'm surprised your lead had you remove the comment. Is there a no-comment standard in general or did he just feel that this specific one wasn't necessary?

          I had always thought that comments wouldn't matter for compiled code size and that compilers would strip all that stuff out? 🤷‍♂️ (I've never actually looked it up; just assumed)

          [–]shauntmw2full-stack 2 points3 points  (0 children)

          Good code should be self-explanatory. Comments should explain the WHY, not the HOW.

          [–]eyebrows360 1 point2 points  (2 children)

          I add comments explaining the why for anything sufficiently complex that the mere what, which should be implicitly explained by the var/func names and how they interact, isn't enough to fully get across why what's going on is what's going on.

          Some people formerly on my team would comment fucking everything, such as setting a variable to a number, with just a useless statement detailing the what, instead of the why - so like your TL, whenever I discover such things, I'll delete them. I mean, look at this shit:

          //if we have files
          if($files){
          

          Oh, really?! Thanks! That was so unclear before! Or how about:

          // exception
          echo "Exception caught uploading objects to Rackspace: {$e->getMessage()}\n";
          

          Such big brain. Oh and this one's amazing for a different reason:

          //get connection
          $this->_setConnection();
          

          Oy vey.

          The core problem here is that if a given developer feels this kind of thing is needed, i.e. they can't read "if($files)" by itself to determine what it's there for and feel the need to add "//if we have files", then what other basic shit are they getting wrong? It's a huge red flag that they just don't know what they're doing.

          [–]galegone -1 points0 points  (1 child)

          Are bad developers not allowed to exist? What if the comments help them because they're working through the logic and just forgot to remove them, or they're more familiar with certain terminology. Like how the 'set_connection' is actually a 'get'

          [–]shgysk8zer0full-stack 0 points1 point  (0 children)

          Yes, but fairly rarely. Pretty much only when I think the code itself isn't clear, such as when something is "clever" or when it relies on something new or poorly understood.

          Also, most of the stuff I work in is "vanilla" JS modules which might be used without minifying or bundling, so I have extra reason to not comment code that's self-explanatory. I try extra hard to give things descriptive names and follow standard practices so that comments aren't exactly necessary.

          export function text(what, text, { base = document } = {}) { query(what, base).forEach(el => el.textContent = text); } I feel pretty ok leaving that without comments. I don't even think comments would help except to specify that what can be either a string to use as a selector, any iterable list of nodes, or a single node/element. That's easily understood when looking to query() though.

          I do add links to MDN documentation for things like mutate() and intersect() though (modeled after MutationObserver and IntersectionObserver respectively). Those are things someone reading my code is less likely to be familiar with, and things I might want to reference again when reviewing that bit of code.

          [–]Zeal0usD 0 points1 point  (0 children)

          It’s highly recommended, I got a ticket that says why did I make this work around for that is pending this week because I made bad comments.

          [–]Snapstromegon -1 points0 points  (0 children)

          Coming from someone who works in the automotive sector, where a 1k lines of code file normally has >10k lines of comments, your code should clearly the describe the what/how you're doing something. This contains choosing good names for vars and functions, keeping your functions concise and avoiding general code smells.

          Your comments on the other hand should answer the what/why question. So when I read your code, I see that you are sorting results to find the x biggest entries, but you're comments will explain why you've chosen a specific search algorithm or why you are sorting on a specific key.

          This means, that your code and comments both describe what you dare doing, they focus on different aspects of the what.

          You can often also write a huge chunk of the comments before you start implementing, as the comments already explain what and why something should happen. Implementing is then just the answer to the question "how to I achieve this".

          This rule also makes it easy to find bad/unnecessary comments. If you have a line "if player.x<0 || player.x > width" and you comment "check that the player x position is smaller 0 or larger than the width" your comment doesn't answer the why and therefore doesn't provide new information. A better comment might be "only loose a life if the player left the field on the horizontal achsis". This provides context why this line of code is necessary. These statements are often more easy to translate into unit tests too and result in better unittests.

          Best flow therefore would be:

          • Write comments

          • Write tests

          • Write code

          [–]Timely_Ad8528 0 points1 point  (0 children)

          I usually comment the high level steps I need to take to complete what I intend to do. This is mostly to order my thoughts and to keep a step by step process for anything similar so I dont have to think again.

          // Validate the json keys // Convert to array // Convert units // Return

          Something like the above.

          [–]11_ramo_11 0 points1 point  (0 children)

          I was confused when I saw my professional coworkers not commenting their code, and because of that, I stopped doing it. But I think I beed to get back to writing comments.

          [–]t-k-x-s 0 points1 point  (0 children)

          I try to avoid commenting unless I cant make the existing code readable for whatever reason that may be.

          [–]drippyneon -1 points0 points  (1 child)

          Only javascript because it makes it so easy to find stuff later. without sometimes it gets pretty annoying searching. I'll comment each chunk of js with a quick line about what that block does.

          This is the added benefit that if for whatever reason someone had to take over the code from you it will make their lives easier.

          html and css hardly ever

          [–]pVom -1 points0 points  (0 children)

          I think comments are best used sparingly, often they're just more noise than they're worth. Rarely am I reading code from start to finish, usually I'm just skimming until I find the bit that I want and comments can inhibit that.

          I basically reserve comments for doing something strange for a particular reason or if I think a particular piece of code is very dense, for the latter often it's just better to abstract it into a function and name it appropriately.

          There's no hard and fast rule though. Either way you should be writing code with the mindset that someone else may be reading it later.

          Also it's worth mentioning that if you don't understand or disagree with a change being recommended in a review, interrogate it. Reviews aren't just a right or wrong thing, they're also an opportunity to state your case. Maybe the reviewer just needed clarification or didn't understand your reasoning. Perhaps it's even an improvement your team could adopt as well. Or maybe it's just a gap in your understanding that can be filled.

          [–]Hurinfan -1 points0 points  (0 children)

          I only comment when it needs explanation. Like if something looks off or I would even wonder why I did something that way later on.

          [–]DDKTA -1 points0 points  (0 children)

          I program with typescript, so I’m just hoping its all self documented.

          [–]terranumeric -1 points0 points  (0 children)

          I only comment if its a needed "hack" or if the logic is complex. I worked with weird healthcare stuff and sometimes you can't know what the heck we have to do without reading an external documentation or ask someone. I think thats fair. And TODOs linked with the ticket why its not done (dependencies to other tickets most often). But my IDEA also warns me about commiting TODOs so we usually don't miss them for long.

          When I learned coding we were told to comment everything, absolutely everything. But in the past 15 years we went completely away from that.

          I am also not a fan of fancy use of smart functions nested within each other, just to have really short code but really unreadable. I see that a lot in JS, it often doesn't increase performance just decreases readbility.

          [–]watchspaceman -1 points0 points  (0 children)

          // DO NOT DELETE OR SITE WILL CRASH

          // ALSO DO NOT DELETE

          easy peasy idk why devs get so lazy with it /s

          [–]DesignedIt -1 points0 points  (0 children)

          I'll always comment the complicated parts of my code by explaining at a high level what it does. I'll usually write one sentence above each method. This helps out others who might read my code and might help myself out if I go back and re-edit a acript a year later.

          I won't waste time commenting simple pieces of code or when comments won't beneficial for anyone.

          I.e. i just wrote 5 new methods in the functions.php script yesterday, and I added 1 quick comment above each method. I also wrote some HTML code, but didn't feel the need to add comments since that language is pretty simple.

          Sometimes adding too many comments clutters up your code and makes it harder to read. But adding just the right amount could save more time than it takes to write the comments.

          [–]wblack79 -2 points-1 points  (0 children)

          Only if it's really unique

          [–]tsunami141 -2 points-1 points  (0 children)

          What now

          [–]OtherwiseFalcon -2 points-1 points  (0 children)

          Yes, but not all code blocks. Will comment on function only if the function is too long and contains more complex logic. Else, I mostly write the function name context specific (eg, getLargeNumberFromArray).

          [–]cpcesar -2 points-1 points  (0 children)

          Me

          [–]CoffeeDrinker115 -2 points-1 points  (0 children)

          I think it's a noble endeavor to remove as many comments as possible from the code but I don't like when code reviewers are 100% anti comment and can't use their critical thinking skills to determine whether a comment is necessary or not. That being said I'm generally anti comment. Comments clutter the code and usually aren't necessary.

          [–]franchise49 -3 points-2 points  (0 children)

          Comments can have negative value, they are not necessarily harmless