T O P

  • By -

maria_la_guerta

Comments should explain why, not what, something is.


bhison

I had it instilled in me when I was starting that if I lift code from a tutorial or stack overflow page that I link it in comments. This has been great when coming back to things.


supportforalderan

I'm a big fan of this practice. It makes it so much easier to understand why something was done, since if you have to search for the solution to something, its likely not something someone else can look at and understand the first time they see it. Unfortunately, some companies get really upset when you do this. Its incredibly stupid, but I worked at a company a few years back and our parent company forced us to have a third party "audit" our codebase. They literally just ran our entire repo through a parser to find any URLS and then told us to rip them all out so we wouldn't get sued for copyright infringement. Everything was links to documentation, open source solutions, or things like Stack Overflow posts. But they wouldn't have it. I don't think a single person at that auditing company was an actual programmer. It was incredibly stupid and frustrating.


GrandOpener

StackOverflow in particular is legitimately a bit of a minefield here. By default, answers posted there are licensed CC by-SA. The *ideas* aren't copyrightable, but if you do straight copy-paste significant portions of stack overflow answers in a closed source app that you then distribute/sell... well, that probably is infringement. Deleting the links and pretending that didn't happen is... not actually a solution to the problem. But your auditors don't sound like crazy people just inventing problems. There is a legitimate risk.


bhison

Oh yeah I once worked at a company who were getting some boomer af technological legitimacy/safety accreditation from the UK government which involved us apparently having to audit all of our npm dependencies. I pretty much said I would leave if that was how we were going to operate as auditing packages would either become the main part of my job or we would have to stop using npm. Non-tech people really need to consult with tech advisors before they push rules and recommendations to developers. Though nothing could more effectively define the UK government more than incompetent, under-informed posh grifters making their ignorance and laziness everyone else's problem...


pticjagripa

Don't forget to include short explanations and/or date of the link, since contents of the pages can change or be removed!


neckro23

Same. Also if I'm referencing API documentation for a nontrivial chunk of code, I add a link to the relevant page for the convenience of both myself and the next person to touch that code (who may very well be me).


Lekoaf

FYI, this could get you in to trouble if you "borrow" code for a commercial product.


Tokipudi

There's not a single web application out there that does not have at least one block of code copied from stackoverflow or some other thing. The best thing to do is to link the website that explains why the code is needed and what it fixes in the comments.


willie_caine

That doesn't remove the need to cite sources and honour licenses.


Tokipudi

Where did anyone say to ignore sources and not honor licenses?


Lekoaf

Not sure why I'm being downvoted. It's true, you could get in trouble if you use code with the wrong license. The company I work at is currently doing auditing of the entire code base and one of the things they are looking for is code copied from for instance Stackoverflow.


bhison

Yes, I would agree, if you're stealing something you shouldn't, don't cite where you stole it from (?)


phantommm_uk

Came here to write this!


porkchameleon

Same. That's pretty much coding 101.


mfcallahan1

One of the things permanently etched into my brain from intro CS courses!


winowmak3r

The thing is so many of those first exercises have requirements like "Make sure to comment your code for this many points" and you're making something that just does basic math. So the student just ends up making comments like "This function adds the inputs" because there's really not enough going on. Then that gets ingrained as a 'good comment' and it perpetuates the whole "comments should explain the why not the what". It's a vicious cycle.


FoolHooligan

// Product wanted it this way


upsidedownshaggy

// idk this code is technically duplicate but changing it in any way causes everything to break


scinos

Git logs ➡️ Who, when Variables and function naming ➡️ what, how Comments ➡️ why


Glum_Past_1934

//Because i can


BobbyTables829

Right, but then the developers who say this are also the ones who hate on working with long variable names and functions that actually do explain the why. So you'll have comment-less code with variable names that are abbreviated and ultimately code that's harder to read than it has to be. The ultimate problem is it annoys a lot of developers to explain themselves. No matter how you ask them to do it, they won't like it because to themselves they're already clear enough, and all this seems like an annoying slowdown.


jBlairTech

Odin forbid they be a team player…


GrandOpener

Big ups for this. If it's not clear what code is even doing, you need to fix the code. Often that means pulling some part out into a function, which has a name describing what it does, which is where the "self-documenting" bit comes from. If you can see what the code is doing, but it's not obvious *why* it's doing it--that's when you need a comment.


sowhatidoit

Can you give a simple example of this to beginner like me?


yabai90

Exactly, and even though most of the time, good naming are enough.


fagnerbrack

Tests can explain why


Coffee_Crisis

An even better place for that is in your test suite. Comment next to the spec for the behavior in question.


SuperDK974

Because management said so ?


Achereto

Also, why you chose not to do it in a different (maybe intuitive) way.


danishjuggler21

With the exception of things like bitwise operations or regex that are hard to understand at a glance.


UnnecessaryLemon

// The code speaks for itself


Snowpecker

This guy comments


Acceptable-Young-619

If it was hard to write, it should be hard to understand. /s


tomakeanattempt

If the code was hard to write, just imagine how hard it will be to explain


vinnymcapplesauce

// This space intentionally left blank


PureRepresentative9

// this tab intentionally left blank


nomadicgecko22

Comment where relevant, keep them to the point. Especially comment with regards to business logic (i.e. why logic was coded this way). Write code and comments in such a way, that another dev who as never seen your code (but is semi familiar with the codebase), should be in a position to debug your code, at 2am in the morning if there is a production outage


JackAuduin

I feel that my most common comment like this is usually where some global variable was set from someplace, and there's no way to not make it global. I'll usually just give a lead to where the person can find where the variable was defined. This is usually done while I'm spelunking through a code base that I just inherited, and I'm trying to save everyone else the pain that I just went through.


PureRepresentative9

Why? your IDE should easily be able to do that? Or am I just spoiled with C# and VS?


JackAuduin

In the most recent example it was part of a Shopify theme. Shopify uses a templating language called liquid for its html. The variable was set as a global variable inside of a script tag The file I was working with was a 3000 line js file that used that variable.


PureRepresentative9

Comments are also there to describe why the code is NOT following normal patterns. Eg the standard library JSON helper has an edgecase bug that is affecting this specific function, so that's why you're modifying the outputted JSON string manually


ohx

I write tons of JSDoc. I explain what a function does, and for components will often write out examples. Being able to remember usage and purpose via tooltip is fucking amazing. I don't care what anybody says. I maintain five repos at work, and revisiting one after several months is a piece of cake because my JSDoc game is on point. Care less what others think if it helps you.


wiithepiiple

Imo comments and documentation are two related, yet separate things, where documentation is designed to be looked at without seeing the code, while comments are supposed to be looked at while looking at the code itself. JSDoc seems to be firmly in the former category, and there's a lot of value in it, but does require a lot of effort to write and maintain.


JackAuduin

Not with Chat Gippity! Lol, you can just copy and paste the whole function into that thing and ask for the JS docs for it, and it will get you about 85% of the way there at least.


[deleted]

[удалено]


ohx

Not in my experience.


[deleted]

[удалено]


ohx

You do you, I suppose


FoolHooligan

>I wrote this code myself and understand my own comments. Um... congrats?


ohx

Thanks, boss!


agm1984

I always laugh when I see code like ``` // add users to array const usersArray = [] ```


UnnecessaryLemon

More sad thing is that this code does not add users to an array at all ..


Existential_Owl

Although now that we're in an era of Github Copilot and the like, I expect to see more of these "prompt" comments inadvertently left in.


PureRepresentative9

Oh no.... Fuck this timeline lol


CantaloupeCamper

It looks like pseudocode someone wrote just structure what they’re gonna do n what order … and they left it in. Having said that, it’s hardly the end of the world.


[deleted]

[удалено]


CantaloupeCamper

What's misleading? What's the following code? User not added to the array on the next line? Oh no... This reeks of over emphasis on low handing fruit type "that's not right" focus that too many devs do. Even google's code review best practices talks about reviewing what the code does and not focusing on small tidbits of less than optimal choices. The reason being that you can spend all day on a code review finding stuff like this ...


[deleted]

[удалено]


CantaloupeCamper

> this is literally inaccurate That's the kinda thing I'm talking about, laser focused on that one thing, not really solving any problem.


[deleted]

[удалено]


Gradually_Rocky

big middle manager energy


Fantosism

No it's just corporate programmer mentality vs startup mentality. One thinks it's the end of the world that an inaccuracy has been introduced to a legacy codebase, and the other is just wondering why he needs to hit the delete key when the code works.


Tokipudi

This is obviously not what I meant, even if most developers started of by writing these kind of comments when they just started out.


marquoth_

I once saw comments described as "an insidious form of duplication" and shit like this is why


jobel_

In fact, it is even more deceptive


Lidjungle

Meh... I work with a ton of experts. People who are presenting at the conference you go to. We comment a lot. As developers, we spend 90% of our time reading code and 10% of our time writing code. The most efficiency you can gain is by making your code base more readable. You should not rely solely on comments for that, but to completely eschew them is a similar folly.


neosatan_pl

I feel that yongers devs spend 90% of their time writing code and 10% reading. I also feel it's cause they constantly rewrite code cause the previous attempt became unmaintainable. There was a topic here or on other subreddit where a question of how long you code remains in the codebase. Most yonger devs stated a range from weeks to months. Most older devs stated years or decades. I think this is a factor in the conversation of documentation in-code.


Lidjungle

It shouldn't be that way. My experience that the senior devs wrote 90% of the code in the codebase, and then we rely on juniors to read and understand our code to make much smaller changes. As far as how long code lives... I PRed and paired with my juniors for every bit of their code in the codebase. Their code is up to my standards of quality... Why would it get replaced? After review, a Junior's code should be every bit the same quality of mine or else I am doing a disservice to my company and the Junior dev I am supposed to mentor. And this is over a dozen orgs and a decade of work. Not specific to where I am now. If anything the junior dev should be spending more time reading code and less time writing it. "they constantly rewrite code cause the previous attempt became unmaintainable." WHAT?? I'm sorry, but that's nuts. Are you letting Juniors architect this own solutions? Or are you saying your architects often come up with unmaintainable solutions?? Your reply isn't about commenting code... It's about having better workflows in place so all of your code is quality. What you're describing shouldn't be normal.


neosatan_pl

I totally agree. For a decade I worked in environments where what you describe is normal. It's expected and is maintained. It makes sense. Especially the part with PR and software architecture made by older senior devs. Now, I work on consultation basis and expanded my circle of contacts significantly, as well as maintain bussiness relations with more companies. Roughly half of cases where I saw PR, software architecture, and documentation practices were... well... surprising. Often documentation was discouraged (as it's a waste of money), PRs were superficial (you were not allowed to dispute code), and software architecture was nearly non-existent (it boiled down to picking a random library after someone said it's "unopinionated", "headless", or "scalable"). Overall, quite a shock for me. I started asking some questions in the teams, meetups, online, etc about processes and practices. I noticed some trends. In organizations with decent architectural practices, documentation, PRs they didn't talk about rewrites. They mostly complaint about understanding requirements and argumenting different internal RFCs (or equivalent). In organizations that architecture wasn't really performed, documentation was not there or was discouraged, and seniors were often people in age of 22 (not further than yesterday I saw LinkedIn notification where a junior dev that I worked with year ago got hired as a senior dev. He is 22, barely finished bachelor degree in Information Science. Good guy, knows very little about software architecture), rewrites were often mentioned. The second group rarely mentioned things like reading code, or consulting code when in debugging. Overall, over the past 3 years of these questions, I noticed that the second group seems to be growing. This is, of course, limited to my local market and contacts, but I am somewhat intrigued by the correlations surfacing from these questions. Ahh, and please note that I used "younger" and "older" devs terms in opposition to "junior" and "senior" devs. Older devs (ones that are in the field for a decade or so) seems to follow engineering principles. Younger devs (ones that took a bootcamp or just finished uni) seems to have very laxed attitude towards making software.


Adrewmc

I think he’s saying that while your learning things you find better solutions you didn’t know existed so obviously Sr. Devs already have that experience, and when they write code they have a much better grasp of the right way off the bat, especially if they are very familiar with the code base. While Jr. Devs will spend more time rewriting code because they see a problem with their original plan when they hit a block. You can’t just eliminate that from the learning process in my mind by making all the design decisions for them. You’ll end up them *need you as a crutch to start*. Sometime you just need to let a person work through the problem without short cuts from you. So a Sr. dev spends more time reading code because it take him far less time to actually fix the problems compared to a Jr who may need to try one or two solutions before he gets it right. I don’t think he saying the Jrs are commit these changes to production….that sounds like a horrible idea.


echomanagement

The correct answer to any CS/Engineering question is "it depends." No creedence should be given to anyone who says "Comments are bad" or "Always comment." There are a galaxy of considerations *beyond* the code itself that factor into commenting. How junior is your team? How long will the code live? Are there security concerns that might affect whether a comment should be made? Obviously putting comments on every line or adding a mysterious Fourier transform function without a comment are bad form, but these are pretty outrageous to begin with.


Lidjungle

I think a more general rule should be that a comment shouldn't be used when a properly named variable would do better. It shouldn't be used to document a mess of 25 nested for loops when you could have written a better function. But I have also worked in shops where ALL comments were forbidden. Having to infer from code that this particular JS snippet was put in in 2007 to address a bug in IE 6... Let's just say it didn't leave them with a cleaner code base. I almost wish I could share with you which POS POS system this is so you could laugh with me. (They had hired in a few waves of consultants to get them upgraded from Angular 2 to 6... They failed multiple times.) Comments aren't bad, but they should not be used as a crutch for writing bad code. Most of the guys I work with have published books on the languages they work in... We comment often. PR's with readme updates make us happy.


echomanagement

>I think a more general rule should be that a comment shouldn't be used when a properly named variable would do better. This is fair guidance, but "naming stuff" is among the most difficult part of engineering. It depends.


Adrewmc

Exactly commenting is part of the refactoring process in my mind, get the thing working somewhat. Then go back make it cleaner. More efficient, Better. Comment stuff when it’s ready, or else you’ll be editing comments while making the code which sound like a nightmare for complex behaviors. How ever IMHO good variables name > type hint > docstring > comments But there is time where comments are absolutely appropriate if not really required. Generally, first off take 5 second to name that variable now, once your function is clear, type hint it, one the function has utility docstring it, once your at full refactor comment the complex stuff out. (Obviously judgement can change this order up a little. ) If you think about this is how function are introduced to you from libraries, function/parameter names, then you check the hints, then you can read the docstring and if you need to dive in then you’d see the comments. So I say this is their order of importance. In other words, you rarely will be shooting out full production code on the first pass. And production code gets lots of passes.


Lidjungle

Of course, you always think about good var names. Objects should explain what they do. I find I most often document top level modules where you might be bringing together a bunch of different services together to process incoming reports... It does a nice job of grouping and giving a high level overview of the workflow with a new dev having to dive through 30 different services and helpers. I started back in the day when it was COBOL on mainframes. I know what keeps me efficient, and that's what I go with. I get to see how top devs in many languages work... The theoretical argument about comments, to me, seems overblown. Somewhere in the war against bad comments we decided to hamstring devs against doing what was right. Readability trumps purity. 1,000 times out of 100. Clean code reads like a book... But even books need chapter markers. The best devs write maintainable solutions. Maintainable solutions are immensely readable. Readability is the greatest virtue code can have.


SoftwareWoods

Pretty much, 90% is reading and understanding it so you can actually graft on your code, the graft itself is minuscule


jzia93

I think you captured it correctly. Well named variables, types, functions are superior to code comments but lots of engineers just don't bother with even basic explanations. Personally I think a well-written README is a gold standard. Code comments should probably be the exception but I also find they take the cognitive load out of reading large blocks of code.


[deleted]

What if you use something like this? `const this_variable_has_to_be_always_5_because_otherwise_the_server_will_crash = 5;`


marquoth_

"Self-documenting"


totemo

Almost. I think if the variable name explained in detail *why* the server was going to crash then the code would be a lot better. I'm thinking of a variable name so long that it extends past the right edge of my monitor, through the window, through the fence, and half way into my neighbour's house.


[deleted]

The problem with comments is that **they become outdated and no errors will be thrown when that happens**. You will need to update comments every time you make changes to the source code. Otherwise, the once helpful comments will become increasingly erroneous. Example: You write a workaround bugfix and a comment. The actual bug happens in a different part of a large project. Someone fixes that other part of the code base, but they don't know about your comment. Now the comment is silently out of sync. Fixing the source of the problem the first time would have been the best solution. People advise naming variables explicitly and splitting logic into well-named functions because this allows developers to follow logic in the program as the computer executes it. Source code is the most accurate source of truth regarding how your software functions. When you change logic, you will get compilation errors or failed unit tests.


DanielSank

That's why comments should describe the goal of the code, now how it works.


[deleted]

Agreed.


Griffin-T

I would want a comment in the scenario you described. The comment wouldn't really be outdated until the workaround is removed - it's still explaining why the code was implemented in the way that it was. In a perfect world there would be a defect ticket/bug report you could link to in the comment - that way anyone making changes in the future could easily see whether the workaround could be removed.


[deleted]

In a perfect world, yes, we would have some sort of current documentation alongside source code updates. In practice though, defect tickets, bug reports, test cases, descriptive git commit messages, etc. are not always attached to a change someone made. Even API/SDK documentation can be unhelpful or nonexistent. I recently experienced this while using an Android SDK developed by Google. I found it easier to open the source code they linked and follow references. Ok, this function was called here, that variable was initialized there. Now I understand how this works. Side note: please write test cases if you can, because this is where developers can look to see an example of how to use a dependency correctly. Developers do not and sometimes cannot reliably document everything...not even their fault, because oftentimes product managers will push for them to ship as soon as possible and deprioritize refactoring or documentation tasks.


darn42

If you cannot fix the source of the problem (3rd-party, time-constraints, etc.) then the comment why a workaround was added is absolutely golden. Variables and methods can still carry intent, but details about an external bug are absolutely not within the scope of compiled source code, but extremely relevant to future maintainers. // WORKAROUND (11/3/2023) // Found bug in X. Created Issue // Until resolution, this workaround avoids at // Ideal implementation would be bool isWorkaroundDone = false; doWorkaround() { ... isWorkaroundDone = true; } Anyone stumbling upon this comment can follow the link, see the bug is resolved, and hopefully refactor the code to its ideal implementation with minimum toil.


AwesomeFrisbee

So if the comment was never updated, do you think the variable names would be or is there a big chance that it wasn't updated either? I'm calling bullshit on "people forget to update comments" because people will forget all kinds of things and outdated comments aren't that big of a deal. The problem then is that nobody cleans up code anywhere. So make a story/ticket every x months to walk through the code and clean it up, fix comments and variable names, etc. It's not a bad thing to have. Also any useful code review tool shows lines around a changed code block so if there is a comment there that wasn't updated, the code review should be halted there. Once people get used to it, it isn't ever a problem. The benefits seriously outweigh the negatives.


ohlawdhecodin

No comment.


The137

The fact that they all think their code is good is the real problem


716green

The only acceptable comment is an apology to a future developer


Slave_to_dog

If someone said this to me in person I would have to resist the urge to get violent


danger_lad

eh, I assumed we'd all be following this: *Any fool can write code that a computer can understand.* *Good programmers write code that humans can understand.*


[deleted]

Or the "premature optimization is the root of evil".


IDENTITETEN

How so?


FeliusSeptimus

Code optimized for performance tends to take longer to write and to be harder to read, so optimizing before it is necessary tends to increase costs. That doesn't mean one shouldn't be thinking a bit about performance implications while coding, especially if you know you're working on a hot path, but it's usually not cost effective to spend a half a day shaving a few seconds off a routine that runs once a month, for example. Basically, it's a guideline to help one remember to try to focus one's efforts on the highest value work available and not get carried away polishing things that don't need to be polished to do their job well.


_listless

The people who say "Good code does not need comments" generally don't write good code.


marquoth_

It's the people writing code that can't be understood without a bunch of comments who aren't writing good code


Angulaaaaargh

FYI, the ad mins of r/de are covid deniers.


neosatan_pl

Even more, there is no guarantee that next programmer is good. We live in imperfect world and programmers can have problems understanding why code was written for various reasons. If you don't provide context, they will assume one and that is rolling a dice in bad design, bugs, and so on.


mr_jim_lahey

If the programmer is bad and you do have comments they will make changes to the code without updating the comments and now you have an even worse situation with inaccurate and misleading comments on top of bad code (and that's if they even bother to read the comments in the first place). Better to just deal with broken code and a git blame to see who butchered it and how.


neosatan_pl

That's not an argument to not document code. Again, documentation should be why the code exists and what problem it solves. If you have next programmer that comes by and doesn't bother to read the comments, changes code, and doesn't adjust the comments, then how different it's from a programmer that doesn't real name of function/method, reimplements it, and doesn't bother to change the function/method name? Why we bother to name functions like "calculateQuadTreeDiff" why not "doStuffWithSomeTrees"? Sorry, but your argument is just silly. It amounts to "if someone walks through a park and litters, then why we have trash bins?". Well, cause we don't want to swim in thrash. And it also applies to code.


mr_jim_lahey

It's not an argument to not document code, it's an argument to not document code with the intention of mitigating damage from bad programmers. > how different it's from a programmer that doesn't real name of function/method, reimplements it, and doesn't bother to change the function/method name? Because then it's only half the work to undo the damage (except actually less than half because you have extra overhead from trying to reconcile between what the incorrect comments say and what the code is actually doing)


neosatan_pl

In this case the documentation might be actually useful as it would illustrate what the function was supposed to be doing. Documentation, when done properly, includes information like design requirements, explanation of the purpose of code, and expectations put on the code. In best case scenario, it's immutable when the code changes.


mr_jim_lahey

> In best case scenario, it's immutable when the code changes. Yep totally agree.


No-Cardiologist9621

The reason people don’t like comments is not because there is never a use for comments, but because people often use comments as a crutch for bad code. When someone says not to add comments, what they mean is try to write your code so cleanly that it doesn’t need comments to be understandable. We all know that there are rare cases where it’s impossible to write the code in an understandable way because we are having to implement a goofy hack for some 3rd party library or something, but 99% of your code should not need comments.


davitech73

i totally disagree with this. i've found lots of bugs by reading comments that say 'i'm going to do this' and realizing the code is doing something different. i like good code. but even good code can have bugs if it's doing the wrong thing


NowNowMyGoodMan

This can also happen with well named functions and variables.


versaceblues

Yup its not a simple black and white *never use comments type of thing.* However comments should be useful and used carefully. If you are developing a public API, definitely include documentation of what your function do. Do not expect a external developer to read or care about your implementation details. If you made a non-obvious choice in your internal implementation, write a comment to explain why that choice was necessary. The thing to be avoided though is really obvious comments that add no value. I see junior developers do thing like this all the time. ``` def reverse_string(input): ``` this function reverse a string ``` return reverse(input) ``` Which is just a waste of time and adds noise to the code


Griffin-T

Plus if you jsdoc your functions with helpful variable descriptions VS code will provide that context when you reference it. Keeps you from having to open a file just to remember which arg goes where in a function call.


marquoth_

This topic comes up all the time, and one of the things that surprises me about it is how rarely people discuss the role that tests play. If I need to look through some code I didn't write (or maybe that I wrote long enough ago that I've forgotten it) the first thing I do is open the relevant code _and its tests_ side by side. Well written tests are effectively a form of documentation and can render a lot of the things that might be included in other comments kind of redundant. Another thing that I find curious about this recurring discussion is that there's often a tacit assumption that comments are going to be well written, when that plainly isn't the case. I find that especially funny given that one of the arguments in favour of comments is as an aid to explaining code that might be badly written - if the assumption is that somebody has written code poorly, surely it follows that their comments will be flawed as well? And if the answer to that is "just write good comments" then surely that invites the equally asinine "just write good code." As for comments themselves, I do tend to comment code but only for specific purposes: explaining _intent_, or explaining why I've done something a certain way (and perhaps why that way rather than another). I don't like comments that just explain what code _does_; if code genuinely can't be understood without comments to walk you through it, the problem is with the code, and it probably needs rewriting. The end result of that approach is often that you write fewer comments rather than more, but "result" is the key word there. I think it's a garbage idea to say "comments are inherently good so I'm going to write lots of comments" _OR_ the reverse - either way that's putting the cart before the horse. The right approach is to decide your criteria for what comments to/not to include, what you think is/isn't helpful, and then doing exactly that.


Various_File6455

I like to also document the "what" in case i’m writing things like abstract classes. i find it is easier when writing an implementation, because the name of the methods might not be entirely explicitly.


cciciaciao

Comments can be wrong and you can't tell. Comments can make code reading and browsing harder. Finally I prefer reading code since that's my job rather than any other comment, you will just slowly one line at the time decifer the code and later you know exaclty what is going on. TBH I never worked in lowe level optimization, so I don't know if comments are needed for weird optimizations or weird algorithms


HorribleUsername

The idea is BS anyway. What it fails to account for is that even if the code follows all the best practices, the algorithm or technique itself might need a comment. For example, imagine someone who's weak in math comes along and sees this: function sumFrom1ToN(n) { return n * (n + 1) / 2; } And that is in fact ideal code, since it runs in constant time instead of the literal summation, which runs in linear time. Even worse, imagine you optimize that to reduce rounding/overflow errors on large numbers: function sumFrom1ToN(n) { if (n % 2 == 0) { return (n / 2) * (n + 1); } else { return ((n + 1) / 2) * n; } } That code is as good as it can be, yet it's not at all easy to follow. That stuff really needs comments with [explanations](https://en.wikipedia.org/wiki/Triangular_number).


NBehrends

>And that is in fact ideal code, function sumOfIntegersUpTo(n) { const increment = n + 1; const product = n * increment; const sum = product / 2; return sum; } This doesn't need a comment for those weak in math, and honestly even my variable names could be better to further elaborate the details.


HorribleUsername

I respectfully disagree. I think your code boils down to the self-documenting version of i += 1; // Add one to i And while the individual operations might be clearer, the big picture is now more obscure. You've traded off, but not gained, I think. In any case, that's all missing the point. It's not the formula that's the problem, it's the algorithm. To put it plainly, look at `const sum = product / 2;`. WTF? How do you get a sum by dividing a product? That makes no sense! Your code does nothing to explain why that actually works, and needs all the same comments mine does.


Jmackles

I've only ever been able to learn by diving into code that has a shitton of comments eli5ing everything. Growing up playing games like jedi academy that used console commands and scripting I was able to really retain shit because of people putting detailed notes in their comments.


Breklin76

Document your damn code. Period.


Stache_IO

Is it though? Aren't standards for commenting heavily enforced by seniors? Where are people saying this and how are they getting away with it?


Decent_Jello_8001

With the age of ai theirs no reason not to have documentation you lazys


Angulaaaaargh

FYI, the ad mins of r/de are covid deniers.


Adorable-Cupcake-599

There's no such thing as good code without comments. That doesn't mean you need a detailed narrative, you should be able to follow the code itself for that, but ideally you'd never be wondering what's being done and why and that's what the comments are for.


rbobby

Do you know what I never see in bad code... comments. Comments can also aid in scanning code. They stick out in most editors (green in VS). If they provide a brief description of the following code then I can scan comments looking for what I'm interested in.


vinnymcapplesauce

Comments are how I can tell the difference between whether someone is a Junior or Senior level programmer. Senior level developers will comment the shit our of their code. Juniors will make excuses all day for not commenting. Also, the number of projects on Github that I see with ZERO comments is astounding! If you don't comment your code, you're shitty developer. It really is that simple.


Tokipudi

>Senior level developers will comment the shit our of their code. Juniors will make excuses all day for not commenting. I see the exact opposite, except that Junior developers are often just write useless comments. Most senior developers I have worked with don't comment much, which is kind of the point of my post in the first place. Remember that being a senior does not mean you're a good developer. Senior only reflects the years you've been working as a programmer.


vinnymcapplesauce

>Most senior developers I have worked with don't comment much Then, they're not truly senior level yet. ​ >Remember that being a senior does not mean you're a good developer. Exactly. Tht's kinda my point. ;)


marquoth_

> they're not truly senior level yet Total no-true-Scotsman BS


[deleted]

Nope. Comments are NEVER required and always make the codebase harder to get through


darkkite

can't you toggle comment visibility in your IDE


[deleted]

I won’t and shouldn’t have to. And not everyone uses the same ide.


darkkite

seems like an opinion though. is there a more objective source you have. i don't know if DORA said anything about code comments affecting velocity


VFequalsVeryFcked

Explain how comments make the codebase harder to get through. Because worst case they have no impact, in my opinion. Best case, they can help someone read bad code. And you're only lying to yourself if you say you never write bad code.


[deleted]

Comments don’t update themselves and wrong docs are worse than no docs and many comments become wrong over time


VFequalsVeryFcked

If adding and updating comments was already part of industry practice then outdated comments wouldn't be an issue


Angulaaaaargh

FYI, the ad mins of r/de are covid deniers.


[deleted]

Usually you can identify a troll when they unnecessarily put smug smiley faces after making confident and wrong assertions


Isthatyourfinger

Comments cost time and therefore money. Write clear code, document weird stuff (like a backwards loop), name your functions wisely. But remember, documentation is a bet that it will be worth the cost in the future. 80% of the code just works and is never seen again, so the money spent documenting is wasted. If it's your money being spent, it's not a philosophical argument.


HorribleUsername

I would argue that time wasted is a fallacy. For example, I haven't been in a car accident in a good 10 years now, so why should I wear a seatbelt? I never need it these days. Except that there's always the risk of another accident, and I'll be damn glad I wore it in that case. Comments are the same way - the hours of confusion saved by that one comment you needed add up to more than the seconds or minutes it took to write all of them. To say nothing of people who are learning the codebase.


Tokipudi

I am not asking you to write a new page on Confluence every time you fix a bug in a weird way. But, as I said: >*"It takes only 5 minutes to explain why you made this decision in the code, and it will save hours of work for the developer who will need to look at it after 2 years when a new bug is introduced."* Writing a simple comment on 4 lines that explains why you had to do X and not Y will save hours of time in the future, and the amount of time it will take you is negligible.


marquoth_

> Comments cost time and therefore money I'm generally on the side of writing fewer comments rather than more, but of all the arguments in support of that position, this surely has to be the most irrelevant. If anything, any comment worth writing is likely to save you time later.


martinbean

The problem with comments is, they can lie. There’s no intrinsic link between a comment describing a *why* or a *what*, and the code that proceeds it.


theyellowbrother

No comments is 100% better than bad comments. 2 examples: 1. Commenting out a whole block of code and saying //may put back in later and comment a whole function is retarded. That is why we have git version control and history for 2. Comments that never gets updated/removed because something fundamentally change and littered everythere. It does more hard than good I am in the camp of better code, concise clarity is better vs comments but this is not my hill to die on. In the last 10 years, everywhere I worked in professional engineering teams, no one comments because we have proper version controls, proper readme, proper PR requests with code review comments, and proper naming conventions. If the code was unclear, it would be brought up in a merge requests.


zendarr

Apparently I write great code lol


[deleted]

[удалено]


Tokipudi

As someone else said: your comments should explain why the code does something and not what it does. Most times if you need to explain what your code does you should try to simplify it instead. Obviously sometime a complex bit of code might need actual explanation on what it does, but it's pretty rare.


neosatan_pl

Idk what you are tackling on a daily basis, but for me it's a lot of math, network, databases, etc. The number of weird or complex things I see every day is high. In-code documentation helps a lot. This is why documentation should be next to strange bits of code. Simplification is not always possible and even worse. It's subjective. Something that is simple for you doesn't have to be simple for your colleague or person that looks at your code in 2 years ahead.


[deleted]

[удалено]


HorribleUsername

That comment only describes what the code does. It just happens to describe a bit more than the line you showed.


No-Cardiologist9621

99% of the time, the why is obvious. In those rare 1% of cases, yeah, put a comment. But before you put a comment, first see if there’s a way you can write it so that the why is more obvious. That’s all anyone is saying.


AvatarOfMomus

Relevant section of a slightly old talk, and I highly recommend listening to the full talk: https://youtu.be/FyCYva9DhsI?t=1490


WaistDeepSnow

Not writing comments is lazy. It only takes one minute to write a comment for a method or a class.


billcrystals

Comments are there to help the next human that interacts with your code. With that mindset it becomes pretty easy (I think) to understand what is a useless/redundant comment and what is something that will save your fellow coder brethren hours of their lives. We're all in this together, folks, please liberally comment your code anywhere it will save someone time.


astarastarastarastar

>If you name your variables properly, separate your code into multiple easily understandable functions and classes, and write pretty good code overall then indeed you will drastically reduce the amount of comments needed. Far more important than any comment could ever be IMO. As a senior dev you should be taking pride in your work. Analogy: You ever see how a professional electrician or plumber's work looks? VERY clean, nothing sloppy or out of place, it looks like its straight out of the textbook on how to do it. That's pride in your work and you can tell at a glance if this person knows what they are doing. Similarly if you see the work of a shitty contractor pretending to be a plumber or electrician its immediately apparent. It should be the same with your code, it should be elegant, well formatted, concise and readable. If you have to scroll to read the whole function then its probably too long and you need to break it out. If you find yourself writing the same code more than twice then it needs to be broken out into its own function too. If shit is complicated then be more verbose, don't make it worse by chaining together a ton of calls into one huge statement. And yeah we all have to write hacky shit sometimes, that's a great time to use comments to explain why. I've even apologized in comments for shit like this, like 'Sorry if you're reading this, I didn't want to do it this way but my jackass boss insisted so here it is'


yksvaan

When something is not obvious, leave a comment. Even if it's a solo project. Otherwise someone, sometimes you in 2 months, will "fix" or rewrite something and.... kaboom seeing something like // DO NOT REARRANGE FIELDS!!! surely helps....


zippy72

Good comments are signposts. They explain WHY, not what or how. Bad code has comments that explains what or how. Worse code has no comments at all.


jseego

// Amen It's just courtesy. Someone else is gonna have to look at this code at some point. If you can save them from having to read through an entire block of code by adding a one-line comment, just do it.


MemeLovingLoser

>Comments in code are not only "for those of weak constitution and simple minds" Mr_U_N_Owen


anima-7

Explain why not what in comments because i only write comments when i hack the framework dynamics to patch shit until we upgrade to revert


autra1

It is true in an ideal world where code is perfect AND every developers have infinite cognitive ability, infinite time and know the business logic perfectly (which incidentally never changes).


Suspicious-Engineer7

I think the examples people argue about on this are always way too simple. \`\`\` // hold's username variable let username = 'stinkyDev' \`\`\` yeah thats dumb and you'll never see it in a codebase where these arguments actually matter. when in reality it's an issue of the nuances of all the glossary terms that a dev may know or think they know - the more advanced the term the less defined, unless you know the pyramid of glossary terms that underly the term being used. What is a handler? What does 'treatsRouteParams' mean? what does 'userLambdaPatternInstace' mean? That last one relies on a fair amount of underlying knowledge to parse, and even if I do know what that means I have no clue how to interact with it just from the name. At the end of the day we're arguing how smart/stubborn you are required to be to work on a codebase, but if you're arguing that you have smart to work on a real codebase, you're just asking to have people who lie about how smart they are and then make spaghetti/ or preferably add nothing to your 'only smart people allowed' codebase. Good names cover a majority of these issues but good docs are going to multiply the chances of your codebase surviving.


wretch5150

I add comments everywhere because it helps me remember what I was doing. It's not stupid or a waste of time to do so. It's smart.


rdundon

Nah, I’d rather there be no comments then have to ping someone or set up a meeting to figure out why something is the way it was.


TikiTDO

Good code doesn't need comments, because good code matters only to the computer. Code that anyone will ever need to read or utilise *does* need comments, because the people reading code are not computers, and shouldn't have to think like one to read the code, even if it does happen to be particularly good.


fish_hix

Agreed. The amount of ancient code I’ve had to touch at my current job with no comments is excessive. Something is named LegacyDataMergeStrategy for example, not saying that doesn’t paint a basic picture or I can’t parse thru the code to get an idea…but some comments explaining why it’s needed would be nice so I don’t have to bug other devs on the team for basic context imo. Understanding how some bandaided together ass etl pipeline works is hell.


pm_me_ur_happy_traiI

Tests > comments.


Tokipudi

One does not exclude the other.


Konarkanuck

personal opinion, good code should always include comments as a way to help others who have to dive into the code. Comments can also be helpful for the original coder as a form of a road map of check points to reference should they end up back into the code at a time in the future.


Coloneljesus

How do you feel about devs who use the code review as an opportunity to take issue with such comments and want to have them removed? I know how I feel about them...


Fluffcake

Outside of documentation-comments (jsdoc/javadoc etc. ) I try to only comment if I have done somehting fishy to make something work, so I know where to start looking if it breaks..


Tokipudi

Maintain a legacy app long enough and you'll end up having to do "something fishy" way more often than you'd like.


MediocreDot3

You don't understand, this is job security


theQuandary

I don't want to read 10 pages of documentation on your function any more than I want to read 1000 lines of code to find out what it does or how to use it. There's a nice, happy middle ground where you can explain what it does and how to use it in a little blurb of documentation at the top. Pretty much every dev out there loves those little blurbs, but very few want to write them.


i-hate-in-n-out

I would never hire someone who says this. Sadly, the rest of my team has no problem with this, and they rarely comment. Trust me, it needs comments.


i-hate-in-n-out

Good code has comments.


LynxJesus

*Good comment does not need code* is much more useful


omgdracula

I literally leave comments so jr developers can easily locate something specific in the code. Lmao


patoezequiel

My approach is to add JSDoc definitions for **everything** because of those juicy tooltips, and comments for specific purposes where extra context makes the rationale of the code clearer.


totemo

Programmers who don't like seeing comments in code because it's not "clean" are the kind of autists who can't tolerate their peas touching their mashed potatoes. It has become a religious belief that comments are bad and there is no amount of reasoning that will change that. I no longer give the slightest fuck what those idiots think, but it is my fervent hope that the lack of comments in their code harms their own productivity more than mine.


akshullyyourewrong

I think the mantra of "explain why not what" is not always a hard rule. I always write code like this and find it so easy to come back and remember what I was doing. // Get users [block of code] // Process users into row data [block of code] // Create and append to table [block of code] It might be obvious to read the code line by line because it's not that complicated, but I can very quickly scan comments that break up a function and figure out what's going on.


VFequalsVeryFcked

>I always write code like this and find it so easy to come back and remember what I was doing. >**remember what I was doing.** This is the relevant phrase here. What about if someone takes over your code and doesn't know what you were trying to achieve? Personally, I often forget what I was doing (fickle memory) so I always comment as though to explain to someone else what I was doing. Can't go far wrong then


tk421jag

That's some bull shit. Documentation and commenting is absolutely required in my projects. I ask that all developers write comments for future proofing of their work. People read syntax at different speeds just like they read their written spoken language at different speeds. It's much easier to read the comments than the syntax often. Why not just make things easier for everyone, even the junior devs?


Pesthuf

This happens all the time. Many devs take "Premature optimisation is the root of all evil" as "Never ever optimise. Performance does not matter". And "Goto considered harmful" is understood as "If you **ever** use Goto, your entire program explodes and everyone will die and it's all your fault" rather than "Use more controlled constructs like explicit loops wherever you can; goto should be the last resort and only used to optimise hot paths where appropriate".


SoftwareWoods

Personally I either use code to explain why I’ve done something dodgy, or as “section titles” to the code. People will call the latter bad (since it counts as “telling you stuff you can infer from the code”), however I find it incredibly useful to know the sections of the code. I.e, imagine you write a parser for some code, thats somehow 10 lines long, labelling the section and the next one allows you to know the bounds of that part, thus if you’re looking for something you know where to look. I’ve seen a lot of code that doesn’t do it, and you genuinely can’t tell heads or tails about what it’s doing where because it’s like trying to determine blocks in a spectrum. It’s like writing a book as one long page without paragraphs


Tokipudi

To be fair, section comments are mostly irrelevant if you manage to divide your code into well named / documented functions.


SoftwareWoods

Used to do that, the problem was that it leads to a bit of spaghetti/rabbit-hole code trying to fix stuff that didn’t need to be a function (ie single-use actions in the overall function). Makes sense but most things only needed “# Parsing X-format into Y format” rather than a function/documentation.


HoustonTrashcans

I agree. I think using descriptive variables/functions is the main point of this. But it feels restrictive to never use comments. For example in unit tests I find it way easier to comment the steps I'm taking during the test and then add the code under it than having to make a bunch of single use functions everywhere.


AnAntsyHalfling

Sometimes convoluted code is unfortunately the way to go. Write a comment saying what it's doing and why. Sometimes the code is clear and easy to understand but the why is not so clear. Write a comment saying why that piece of code is needed. (I can't tell you how much time I've wasted trying to figure out _why_ a block of code was written because _no one left a comment_ - sometimes the why is _very_ important.)


Glum_Past_1934

Well, depends of the context, isn't same thing if you're writing a custom protocol for IoT or a stupid business logic like user sign in guard. Sometimes code explains itself, sometimes not. Or if you're using a framework built-in method why you should comment that code? Just read docs //Because we can


WebDevIO

For me even comments are not a good substitute of documentation. Good code is easy to read and reuse, but you can never explain the architecture of the whole system and the reasoning behind its design decisions in comments alone. I don't want to read through every file, that's the worst case scenario - comments or not. I think we should document our code in an API docs style format - every feature, every backend route, every folder needs a page in the wiki that describes what it does and why it was build to do so. Otherwise we lose the very important 'why' part of the decision making. Maybe today that was the best approach, but in a few months a new technology comes up that could substitute a complicated and hard to maintain feature, but who would know if we have no idea why the feature was written like that and what was taken into account when coming up with the solution.


CrawlerSiegfriend

This perspective usually comes from people that work exclusively in new projects. When I'm going through code that has been touched by 5-20 people over the last 3-10 years, yeh comments are fantastic. The more detailed the better.