r/AskProgrammers • u/Away-Intention-8723 • 18d ago
"good code shouldn't need comments"
I have heard this saying a couple of times and I think it is the stupidest thing ever. It might be just because I have only been coding for 4 years, but I have never thought to myself that someone's code looks cluttered because they explain what every function does in a one or two line description. If anything it makes the code easier to understand in my opinion.
However, I may be wrong. What do other people think, do yall like code with minimal comments, what are the benefits of writing it that way?
8
u/IAmADev_NoReallyIAm 17d ago
Ok... here's the deal... your code should be usign descriptive varibales and doind things in a clear and decisive way that makes it obvious that you don't need comment to explain what you're doing. The only time you should be using comments is to explain why you are doing something. This isn't the 80s where space it at a premium so, and we're not using assembler here (hopefully)... so break out those descriptive variables, and let the code talk for itself.
Use comments, but only when you need to describe why you're doing something. Other than that, you should be able to look at a piece of a code and see what it is doing. A for loop is a for loop... you don't need a comment that says "loop through, blah blah blah..."... just looking at the code should be enough for you to see that.
Now, if there's some cooky logic... I've included that sometimes as comments... usually because I write those out ahead of time when I'm planning things, then implement it in between... if it' crazy enough, I'll leave it in place, but more often than not, I delete those too.
→ More replies (15)3
u/6a6566663437 17d ago
One reason for “what” comments is sometimes the implementation is wrong. Reading what they’re trying to do helps debug the problem.
Something like every line is excessive, but a summary of what a good-sized chunk is supposed to do is helpful when someone has to come fix it long after it was first written.
→ More replies (11)
14
u/kneebeards 18d ago
One time a coworker said this to me. I had seen his code. I burst out laughing.
5
u/mjmvideos 18d ago
Of course I like code whose comments answer the exact questions I have and omits all comments about stuff I already know. And a good coder should implicitly know which is which. ;-)
→ More replies (1)
5
u/RishabhRD 18d ago
Actually I have seen the both extremes and the real correct way is following design by contract.
So, the idea is we want to write correct code. But what is correct code? Correct code is the code which matches the specifications. But, where is specification? It should be in contract of functions. So, every function should have documentation comment of what it does and what are its preconditions. The function is correct if the function implementation matches its specification.
Similarly, every class should have contract of what it is, and every data member of class should have contract of what it is. It helps specifying what is the entity and the parts we used to make the entity. Why contract for data members? Because, they also might have some invariants present. For example, alignment field should always be power of 2. So, contracts help specifying those invariants that correct implementation have to follow.
And that’s it. You rarely need to write other kind of comments. Very rarely to explain the reason behind surprising implementation. But mostly try, if you need to write any non-contract comment, maybe you are missing an abstraction waiting to be discovered. Maybe there is some class or function missing from your design.
→ More replies (15)3
u/RishabhRD 18d ago
Also it allows you to actually recognizing which code to blame for the bug. If the function doesn’t satisfy the contract when preconditions are satisfied, the function is buggy. But if caller doesn’t satisfy the precondition itself, the caller is buggy not the callee.
Also, remember bugs are not same as runtime errors. It helps you from doing defensive programming and throwing runtime errors for bugs.
3
u/Hour_Sell3547 17d ago edited 17d ago
If code is information, comment is noise. Think about it, who exactly are you writing the comment for? Is it your manager? The HR? Any other non technical guy? Why would they even read the code?
A programmer should (and will) read the code faster than a half page comment describing the same thing under the comment. He has to then read the code anyway to confirm.
Besides, comments are the first sources of drifts. You change the code and then you forget to change the comments. Or, now you have another thing to worry about besides the implementation.
People are not disciplined about comments. A comment loses its value the further it is from the target code. A common case of Javadoc style comments: the thing you're describing there is happening 40 lines below.
It's not that comments are not necessary, you can absolutely use it to describe intent, reasoning, to explain the "magic code" (which not necessarily is good code, but sometimes unavoidable).
The good code does not need comment describing what it is doing, it is self documenting. The companion unit test suit describes the requirements just fine (does not have to be TDD).
Comments can be source of confusion too. Language barrier is a real thing when it comes to comments. It depends on how well you and your readers know English (or whatever other less communicable language you're using). There is no compiler to check what you are writing, unlike the code.
I'm not betting on your literature skills, I'd much rather look into your code. If I don't understand why you did something in a particular way, only then I'll look for comments.
So, keep them minimal. The source file remains less bloated and smaller.
[Edit: fixed typos and spacing]
3
u/Ordinary_Variable 17d ago
Assuming you can read code, people should name variables and functions obvious things.
Eg:
function calculate_radius(x, y, z){
return <some complicated math>
}
Then you have a main loop that calls functions one at a time and has simple logic like "if(check_radius() != 0){draw_circle()}"
This is how NASA writes code. A human can quickly read the logic to see what it does by looking at the main loop, and the names of all the functions are descriptive. Then they can go to those functions and read what they do because the variables' names are also very descriptive.
I've seen code written like this. It hides the complex tasks in functions that you don't need to read, unless you are fixing a bug. And you can search for the variables because you know what they are called. In the above example, if the circle is the wrong size I can simply search the entire codebase for the word "radius" and I will find everywhere the radius was calculated, called, or referenced. It makes bug fixing so easy.
Describe things well and you won't need any comments except for complex math or links to web pages where they explain a very complicated concept that would take pages to explain in a comment.
→ More replies (4)
3
2
u/zackel_flac 18d ago
Like with everything, it depends. In theory a programming language is already a neat abstraction of the machine language (which is not human readable at all), so the code in itself should be self explanatory. If you do: open(file). You don't need a comment that says: it opens a file. This is redundant and useless. Now if you say: "this open triggers a kernel interrupt required to progress", the intent was not clear and so the comment was useful.
Now good code usually tend to have few comments. If you need to explain what you are doing all the time, it means you are not breaking down your architecture in a clean enough way.
2
u/Slight-Living-8098 18d ago edited 18d ago
Sure, you may understand your code now. It's fresh in your mind, the libraries you're using are current, and you just browsed those docs yesterday. But come back to it 1, 5, 10, 15 years later and it's all Greek again.
Comment your code.
My code usually starts with comments. I use them as the outline for the code before any code is even written, for crying out loud.
→ More replies (4)
2
u/CranberryDistinct941 18d ago edited 18d ago
A better way to say it is: "comments aren't the only thing that should make your code readable"
2
u/Winnipesaukee 17d ago
I've gotten to the point where sometimes every line will have some sort of comment and a paragraph stating the purpose of the function, what it accomplishes mathematically if applicable, and roughly what should be input into it and what is the expected kind of output.
I do this because in a few months I may have to revisit it and wonder what fool wrote it. And I am the greatest fool of them all.
→ More replies (5)
2
u/-Wylfen- 17d ago
Good code shouldn't need comments to explain what it does.
Comments should only explain why it does something, what the underlying business logic is. The code itself should be readable enough to be intelligible by itself. That's ideally, of course.
Now documentation is another thing…
2
u/Shadyrabbit 17d ago
Rule of thumb : Well written code is for when you are at work, adding a feature, comments are for when it's 2am production emergency and you are 2 whiskies and a white monster into your night.
→ More replies (2)
4
u/CorpT 18d ago
No one that should be listened to says that.
4
u/guyincognito121 18d ago
I was told this in an interview once, then wrote out a segment of code that employed the CORDIC algorithm to do an atan function with no comments, and asked what him it did. He had no clue--just as I had no clue what it was when I saw it in some firmware I was trying to fix with no comments and minimal documentation. And the reason I could write it out on the spot was that I had spent so much time examining it before figuring out what it actually did.
→ More replies (7)
1
u/Misophist_1 18d ago
D'accord. It's just a matter, what is commented.
Firstly, comment your intention; that is *what* you want to achieve. Then how you are going to do it, i. e. what algorithm you use.
1
u/mtraven23 18d ago
I like to keep it concise, but I dont hesitate to elaborate on some I think might confuse me or someone else in the future.
1
u/killz111 18d ago
There are often 10 different ways to do something. You choose one way cause of certain constraints in certain edge cases. Some idiot comes along and refactors because they think it's more efficient. The app blows up.
It's equally true when you work with AI. It will want to update your code to make it more standard to normal.al practices unless you say in the comments why a particular way is chosen.
On the flip side, someone who reads the code deeply and understands the application domain can often reverse engineer the requirements or design from the code. But those people are the minority
1
u/Liam_Mercier 18d ago
It's like any rule, it depends. I usually just comment whenever I think the implementation needs explaining, or I used some combination of external library code in a way that might need an API lookup, or If I think the goal should be explained. We have comments for a reason, it makes it easier to read in 6 months when you don't actually remember the implementation verbatim.
That doesn't mean you shouldn't do a good job with naming entities. For example, if you're making a C++ container, you likely want to include some sort of size() function with the same expected semantics as other containers. You don't need to explain what size() does, because everyone knows what it does, just like how they know what empty() and capacity() do.
Of course, it's inevitable that some people will disagree and say you should barely comment, other people will say you should comment religiously, you will never really find consensus on anything style related.
1
u/burnt_floppy 18d ago
I personally think there needs to be a balance. The problem with comments is that only certain kinds of coders will see the need for your comments, and the general coder attitude mirrors what you are complaining about...that comments are unnecessary.
Coders can keep assuming any sort of explanation is bad, but its on them when they forget the purpose of their code block next week.
1
u/Beniskickbutt 18d ago
Generally yes, you shouldn't need comments. You will always run into some cases where they are helpful though and it makes to add them when necessary.
One big problem with comments is that they often get out of sync
1
u/jonwolski 18d ago
Good code SHOULDN’T need comments, but “should” is doing a lot of work in that saying. This is expressing a quality of ideal code: that the intentions of the coder are revealed adequately in the variable names, function names, and. types. After all, what do you put in a comment that couldn’t go in a function name or variable name?
Since we must make trade-offs for performance or other reasons, we approach but never attain the ideal, and we must supplement our best code with comments and even documentation.
1
u/AlexMTBDude 18d ago
Whenever you read examples of absolute truths in our business, where complex things are expressed in simple terms, and words like "never" and "always" are used, it's mostly bullshit that sounds punchy.
1
u/Playful-Ad6659 18d ago
This exact phrase, of course, is ridiculous, but it is also not really what people generally say. I'm sure some people say and even believe, this, but generally speaking the idea is that the code should be easy to read and understand, and thus not need comments. Why write a comment explaining what a function does if the function can just be named to explain what it does, for example?
Comments need to be maintained just like code. You should not write them if you do not need them. They can have mistakes, they can, and often are, not updated when the corresponding code is. This does not mean they're bad or should not be used, but they should only be used when there is a good reason to use them.
You will find in your career that sometimes you have to do unusual things to correct a bug or improve performance or whatever else. You know the code you're writing, however hard you may try, will end up confusing to someone down the road. Times like this are an example of where the "risks" of using comments are easily justified. Another place you might see comments is on public or boundary functions meant to be used in a library or api style fashion, and so on.
The idea is to write clear code that shouldn't need comments whenever possible. You should not use comments unecessarily, and you should not skip commenting when necessary.
1
1
u/aktentasche 18d ago
Obscure details that take more time understanding reading the code than a comment should be commented. High level design belongs in dedicated documents.
1
u/Salty_Dig8574 18d ago
When I write code, the code tells you what it does. If I use comments, it is to explain why I did what I did, because sometimes that part is unclear.
1
u/EventRelative2959 18d ago
Comments aren't really all that necessary for explaining what code does, they are better for explaining why it is doing it. Code should be able to explain what code does.
1
u/Distdistdist 18d ago
Good code doesn't need comments. It is true. Been coding for 25+ years. Confirming what you heard.
1
u/Square-Yam-3772 18d ago
there are many schools of thought in coding and that is just one of them. the opposite school thinks every method should have a formal description and every input/output explained. There are other principles like "comment first, then code" blah blah blah...
the one you are referring to basically argue that good variable naming and good flows should be enough to make code readable
none of these are hard science; in the coding realms, we call those "religions": like 2 spaces versus tab or functions can't get over 30 lines or whatever.
I assume you aren't working if you are asking this question so... just follow whatever your professor suggests if you do get some internship.
just be a follower for a while until you know enough to find your own religion I suppose
1
u/Leverkaas2516 17d ago edited 17d ago
I'm with you. There's a ton of information that isn't in the code. Comments should be brief and avoid distracting from the code, but the code itself is never enough.
I have a colleague who isn't shy about making classes, but there is never even a scrap of information about what the class is for. Think the name of a class is enough to explain its purpose and how it fits with the rest of the system? No. It isn't.
Comments convey intent. They tell you what the code is supposed to do or how it's supposed to work. They're vital when there's a disconnect between what you intend, and what the code actually does. The only possible way you could get by with no comments at all, even if you thought it was desirable, would be to write code that is flawless. Nobody does that, nobody CAN do that, so if you have no comments, you are essentially claiming that all the bugs in the code are exactly what you intended.
1
u/Alarming_Try_1968 17d ago edited 17d ago
To quote someone better than me by far at programming a comment is a chance for your code to be wrong twice.
What that is to say if I may be so bold is a comment is an opportunity to add additional information about why you did something that isn't intuitive. Now, there are situations where you need to do something that isn't obvious to the reader of the code:
// this code is in a hot loop that iterates 300k times per frame, by shifting the flag from a separate enum into the unused high bit of the state flag we allow the prefetcher to pull in the complete state per item saving 25% cache misses
item.state |= (obscureFlag << 63);
^- this is a useful comment, sometimes at the end of the day, wierd shit has to happen, but that should be the break glass in case of emergency fallback
// keep track of how many fishes have a flag set
flagSetCount = sum(allCritters, hasFlagSet);
^- this was a redundant comment when it summed allFishes, its just wrong now
in my experience 99.9% of comments are the second case,
Look sometimes we have to compromise, sometimes the time runs out, sometimes we have to eek out that last 5% of performance, but a comment [in the definition of code not the declaration], is saying "Hey, this code is unintuitive and hard to read, here is what it does", there are cases that is the best path or the best you can manage, but 99.9% of the time the correct action isn't comment this code it's fix the code.
1
u/redditor7691 17d ago
My response: You can manage your personal projects like that. This isn’t your choice, it’s the company’s code and we want it commented so others can help maintain it.
1
u/OtherOtherDave 17d ago
Sometimes it’s totally true, especially with small codebases.
As a general statement though, I disagree. If nothing else, Doxygen and such are nice.
1
u/No-Slice-5926 17d ago
With the age of ai, I better get god dam comments. No reason not too
Preferably just give me handoff.md of the problem.
1
u/tomysshadow 17d ago edited 17d ago
I disagree with the idea that good code doesn't need comments. So much of writing code is anticipating the ways that your collaborators might look at a correct piece of code, think "that could be simpler" and change it in a way that causes it to break. Comments are one tool to do this. Tests are an even better tool, but sometimes you can arrive at the right result the wrong way. Comments are the "explain your math."
This is especially true with AI. If you copy paste some code to ChatGPT and ask it to fix something, it does not know what the spec was. Looking only at code with zero comments, it has to attempt to figure out what requirements were being met based on vibes. It can't know "this code was written in this way to avoid compiler warning XYZ" unless something spells that out. And if you don't use AI, someone else happily will, and will make that mistake for you.
Function names and variable names basically are miniature comments. The computer does not care what names they have, which is the basis of e.g. minified JavaScript. So to say that you can't have explicit comments is kind of an arbitrary cutoff point: "you can only convey information helpful for human programmers in the form of one or two word names, not sentences."
Good comments can save a great deal of time and confusion.
1
u/ZappitDev 17d ago
What can be expressed as code should not be written as comments.
Most of the time extracting a variable with a meaningful name or extracting a function that has a clear name explaining exactly what it does is all you need.
Comments are needed if some context is needed to explain why a particular code is written the way it is.
1
u/DiscountFit9224 17d ago
I'll add comment no matter what people say. I've experienced going back to that shit and couldn't understand what I was doing when I wrote those. You do you
1
u/oplukana 17d ago
you are wrong. i try to have basically no comments. you dont need comments if you name things right. the method name should say essentially what the comment would have said. the varible name should say essentially what the comment would have said.
its not about clutter, its about spooky action at a distance and enabling bad code.
someone writes a comment about "hey this following line will call this method on this other class, and that method will serve this current function by doing X, Y, and Z" and then that function in a different file somehwere else changes, and the person that changes it doesnt know everywhere that has a comment which may no longer be true. so now you have comments that lie.
why do you need to write the comment? because the code is bad - because the structure and naming of the things in the code do not make it obvious what they do.
1
u/TheGronne 17d ago
Comments should never explain what, how, or when something is done. Comments should explain why. And they should only exist if the why is not readable from the code. For example a few years ago I added a comment that we run the same function twice, because of a race condition bug in the browser FireFox. That's a why. And a good why. Because even if the function was run under a "If browser is firefox" nobody would be able to tell why we would run the function twice.
However, anything else that can easily be interpreted from the code, shouldn't have comments. Because:
Comments grow stale very quickly. A tiny change or small refactor, without remembering to update the comments, can lead to the comment actively doing harm. And it's not like the compiler could throw an error if the comment is wrong
If you force yourself to never write comments, you also force yourself to write good variable and function names. Not a single person needs a comment saying "Send api request" and a function named sendSpiRequest.
Files get longer, comments clutter the actual functional code. You can see less code on screen at a given moment.
1
u/Brief-Stranger-3947 17d ago edited 17d ago
I often have a hard time to understand, what my own code is doing, when I look at it several month later after I wrote it, so, some comments are useful for myself and for other people working with my code. Modern languages have formal doc strings as a part of the language, and these are much better than scattered comments.
1
u/InterestsVaryGreatly 17d ago edited 17d ago
Good code is written in such a way that someone who isn't a programmer can roughly understand what is happening. Functions that actually describe what is happening, no magic numbers, no egregiously long lines with convoluted logic pathways. If you code in this way, it often helps ensure that you aren't overcomplicating things as well, something that is very easy to do and then just explain away in the comments.
A big problem with comments, and any documentation really, is they don't have to stay updated to code, so if someone changes the code, the comment can be outdated and not match it.
When there is something odd, like a workaround because there is a bug in a dependency that can't be changed, then that needs comments to explain the weird behavior.
The other benefit to writing code that is readable is it tends to explain exactly what is happening in a fairly concise way, whereas people often get overly verbose about things that are extremely obvious in just a glance at the code.
Edit: another important consideration, if you have comments everywhere, people become blind to them and can easily miss or ignore something extremely important (such as why this bass ackwards implementation cannot be updated to the new spec because it breaks XYZ), whereas if you use comments very rarely, the fact that those lines have comments is a big flag in and of itself, and massively reduces the chance for someone to miss it.
→ More replies (9)
1
u/TedditBlatherflag 17d ago
Comments are for why, unless the how is really tricky, unless you don’t work on the code often, then I narrate it like a play by play commenter.
Or used to be anyway. Sigh. I hate this timeline.
1
u/weepejw7 17d ago
Most of the code comments I read are wrong, then sometimes the comment is "right" but the code is wrong.
Also comments are DRY.
Write good code instead, not even minimal comments.
1
u/Inf229 17d ago
It's not that comments are bad. Use them when necessary. But your functions should do what they're called, vars should have names that make sense, and the relationship between classes should be intuitive. If you have to have a bunch of text explaining that this class does that and it needs a thingo and you should read this bit upside down and this bit only works on Sundays etc then your design probably needs a rethink.
1
u/Even_Gap_2253 17d ago
Public APIs should always come with documentation. This also includes functions other team in your company might reuse
But if it is just internal, avoid as much as possible unless you need to explain something non-obvious
1
u/PantomimeVillain 17d ago
It’s not that it shouldn’t need comments. It’s more that the code should comment itself where possible. Like move a section of code into a function that has a name that describes what it does. Use temporary variables where possible that have names that describe what they hold. Just every time you think you need a comment consider whether you can make the code more legible to remove the need for the comment. Sometimes you can’t and that’s ok
1
u/scritchz 17d ago
First off: In my opinion, the statement should only apply to regular comments; documentation comments excluded, because these should be added to any public API.
Apart from that, I think good code should be well abstracted and generally readable (good naming, indented properly, etc.). In being so, there is little need for comments.
I especially want to point out writing well abstracted code: If you were to explain someone how to open the lid of a glass jar, you would say "grab the lid tightly then turn it", not "extend your hand toward the lid-sided end of the jar with your palm facing the lid, move closer until touching the lid with your palm, then wrap your fingers of the lid-touching hand around the lid, where 'around' means around the circular face of the lid instead of the flat top part ..." (bro how do you open a lid). There is benefit to staying at one (high) level of abstraction instead of mixing levels of abstraction; or worse, being specific and detailed (e.g. resulting in a few hundred function lines).
However, there may always be a need for comments: Last time I worked with a framework whose documentation stated that only integers are returned from a function. But it turns out it sometimes returned the integers as strings (damn those dynamically typed languages). In this case, I added a seemingly redundant type-cast along with a comment that explains this inconsistency.
1
1
u/Exact_Ad942 17d ago
Readable code eliminates the need for comment about "what" and "how", but you still need to comment about "why" in some cases.
1
u/Em3rgency 17d ago
Let me give you an example. I have a class called "TimeAtDoorService", it has a function "calculateTimeAtDoor", this function calls other functions, that are named like "getGeoAreaTimeAtDoorModifier" from other services in series and then sums the result and returns it.
Each parameter, both of the class and each function is similarly named. The entire code base follows a very similar structure.
So assuming I know what "time at door" is, which I should, as it's a client business requirement, then all of the code is self documenting and nothing really needs comments. Each individual piece is simple, small, has a single responsibility and explicitly states what it does.
The only time I need comments is when I do something unexpected, like have some special handling for UK postcodes and Ireland eircodes for example. This is a quirk from the real world that only someone familiar on the topic would know, so THAT is where a few comment lines are useful.
But code? Good code doesn't need comments.
1
u/Passenger-Just 17d ago
Comments are an excuse for badly written or confusing code. In a perfect world they would not exist at all. So they need a really good reason for existing. 1:200 lines is a pretty good ratio.
1
u/seanv507 17d ago
So good code should not comment what it's doing, but it should comment why.
Separately, in Python the docstring comment describes the interface (ie how to use the function, without knowing the code)
The problem is that most functions cannot be described with a 1-2 line comment. So either you don't comment the actual complexities that would benefit from comments, or you end up with a very long description.
So typically comments document only what is easy to comment.
The alternative approach is to simplify your code so comments are not necessary. Similarly, your testscode provides documentation on gotchas etc.
The advantage of code changes is that they are more likely to stay up to date. Ie if I change the working of my function, the test code might break (and force me to update my tests), comments willjusts rot...
1
u/Infamous-Bed-7535 17d ago
Good code is dense and packs high-level of abstractions. Kind of continously readable and you have a full understanding what is happening.
Useful to add a few one-liner inline comments.
So yes good code is fine without comments, but always add those
1
u/dphizler 17d ago
I put comments of what the code should do before implementing a feature and slowly I replace comments with code while making sure things don't get too cluttered
1
u/Gwaptiva 17d ago
Human language is full of ambiguities, implicit assumptions, cultural values, nuances of meaning. Code is unequivocal.
Mind you, with AI comments are back in, and way easier to keep uptodate
1
u/AntiCitizen6 17d ago
I was always taught that comments are not only for other people that may have to touch the code, but for future you as well.
1
u/VegetableAstronaut19 17d ago
The point of comments should be explaining explicitly blocks of code where it is unclear what they are doing, even if you have used descriptive naming.
For example, if you are checking that b divides a you would probably write:
if (a%b == 0)
If you were to leave this uncommented it could be unclear what you are doing, and to use descriptive naming for this would need you to make a redundant variable/function. Therefore a comment is the best option.
3
u/Calm-Medicine-3992 17d ago
Disagree. That comment is redundant because the code already reads that way.
Now, if a%b == 0 has a deeper inference that isn't obvious in that section of code then a comment is helpful.
→ More replies (1)2
u/plcdfa 17d ago
If you mean adding a comment to explain why you are checking if a is divisible by b, sure, that may be useful. If you would just add
//we're checking if a is divisible by b here
then no, that should never be necessary. If someone reads the code who's not familiar with the basic syntax and operators they should not be reading (and definitely should not be changing) the code at all. And that's not elitism, it's just not a practical way for a person like that to understand what a piece of software does. They would be much better off reading the documentation or having an LLM explain it to them.
My personal rule of thumb is: your comment to code line ratio shouldn't be more than 1:100. If you have more you're either commenting stuff that doesn't need it, which just adds noise and makes reading it harder, not easier; or there's too much "magic" in your code, which is something you should address anyway.
→ More replies (7)→ More replies (24)2
u/wcneill 14d ago
That code literally says "if a mod b", which by definition means "if b divides a with zero remainder"
Why would you ever, ever comment that? The only engineer that doesn't know what that means is an AI prompt engineer.
→ More replies (4)
1
u/RoseboysHotAsf 17d ago
Most comments i see nowadays (especially cause of ai) are
// 🚀add a and b together
int c = a + b;
1
u/No-Entrepreneur-7740 17d ago
In my experience about 70% comments are outdated, wrong or wishful thinking.
But yeah, I agree they should be an exception that describe some non obvious general intent rather then implementation particulars.
If your naming is good, your code properly encapsulated and your logic clear, your code should be understandable.
1
u/SmokeMuch7356 17d ago
Smoke's First Law of Documentation: Don't document the obvious.
Corollary to Smoke's First Law: Write obvious code.
Comments have to be maintained along with the code they document.
Good code shouldn't need an excess of inline comments. You should absolutely have documentation headers for each function with short, high-level descriptions of the function's purpose, inputs, outputs, return value, and any exceptions thrown (if applicable). Don't just restate the algorithm in English (or whatever), explain its role in the larger program.
Inline comments should be kept to a minimum and should be reserved for code that's not straightforward. It should not only describe what the code does, but why it was written that way.
1
u/Aggressive_Ad_5454 17d ago
Agreed, comments are not a useless waste of time. Read up on module and method comment standards. Depending on language they’re called Javadoc, Jsdoc, xml comments (c#), docstrings (python), PhpDoc, doxygen (c++).
IDEs understand them and help generate them. They’re a huge help for a modest effort.
Good code needs these comments.
1
u/regular_lamp 17d ago
I think this is mostly a backlash to dogmas about very verbose commenting that result in people just restating what the code does (and not how or why).
1
u/iqisoverrated 17d ago
Code often gets fixed/updated/modified over its lifetime...and in this process comments often get overlooked. This way you can end up in a worst case scenario: when the comments are at odds with what the code actually does.
So what do you do when you stumble upon something like this? Is the code wrong and you end up (erroneously) rewriting it to fit the comments? Or do you just 'fix' the comment and ignore some possibly wrong piece of code?
Good code should be like reading a paragraph. The code should be very clear on what it does by its flow and naming of methods/variables/etc,. If you need to tell someone with extra narkup what it does it isn't good code.
This can mean that - particularly in a team context but also if you want to be able to understand your own code a year from now - you intentionally don't write "hacker code" where you try to scrunch every bit of functionality into one line.
Yes, it's 'cool' to write short/concise code. Yes, it feels good when you can write GTA6 in one line of code...but remember this advice:
"Always imagine that the next guy who has to maintain your code is a homicidial maniac who knows where you live"
1
u/bluefishcrab 17d ago edited 17d ago
After a decade working in legacy code, this is bogus. "Comments can be wrong" is a concern that is way overblown. A lot of code is written for concerns or designs or architectures which don't exist anymore, but its still in there, like vestigial legs on a snake. I've seen orders of magnitude more "we can't touch that, every time we do it breaks, but we don't know why or what this acronym here means, or why we have this buffering here" than "wrong comments."
A good comment explaining why something exists, why something was done a certain way or why a decision was made or not made, can save hours or days of work. Especially in million+ line codebases, and/or in long lived OOP code, where data and logic is shredded into a constellation of a thousand pieces.
I don't want a comment for every line, but "we're doing this because this thing interacts with this other thing, and we tried this thing first, but that failed because _____" embeds the history of the project in the source code where I can find it after people leave.
1
u/djchunkymonkey 17d ago
That is bogus. Unfortunately, some programmers are very snobby. It just looks good to them. You have to think about the junior developers or someone that is not familiar with the codebase. You don't want comment on obvious lines or blocks of code-- code littered with comments is not good. That's the level of an introductory programming textbook- so we don't want this. The middle ground is where complex ideas can be written in straight-forward english for others to understand.
For example, if I see an exception that is caught but kind of just swept under the rug, I would like to know why in a comment or two.
Or if I see a one-off exponential back-off retry strategy with some parameters for some service. I would like to know why those parameters are chosen, and what's peculiar about the service. Without good comments, I would have to go git/jira/etc and hunt down the person that made those changes.
1
u/overlookunderhill 17d ago
A good general principle is that comments should describe what the code cannot. Rationale behind a decision (especially one that might be unexpected) real world business context, known pitfalls, etc.
1
u/et_theextratestic1e 17d ago
Takes up too much space in the code I can view.
Plus, as this was originally attributed to a known developer decades ago: you should be able to read the code and know what it does.
If you need a tutorial, look elsewhere.
1
u/Crazytje 17d ago
Naming is important, never forget that, method names and variable names are important, it tells a story.
But, a name is not always enough, if needed, you need a description so the story is told and read more easily.
Good code and good comments should make code read like a good novel!, both are needed.
Just, for the love of good, don't let AI generate your names and comments, you can use it to help, but change it, please 🥺
I know some will think why allow any AI generate names and comments, just remember English is not everyone's native language and it can help format and guide you.
1
u/TheMikman97 17d ago edited 17d ago
Self documenting code doesn't really refer to function signatures. You should comment those specifically so people using them don't need to look at the code to understand them.
The fact about self documenting code is referring to the inside of the code blocks being clear enough in it's behavior, naming and implementation that any additional comments would just be repeating something obvious.
Sometimes that's not possible and that should also be commented, but when it is, not leaving a redundant comment can actually improve readability and make understanding it simpler, especially if it gets changed later and somebody forgets to update the comment
No comment is infinity better then a wrong or misguiding comment
1
u/DrUltimaMan 17d ago
Code is not self documenting. That was always a bullshit notation peddled by "clean code" extremists.
Today however it hardly matters, nobody looks at code except in PRs, and the agents are usually the ones describing what the code does.
1
1
u/Watsons-Butler 17d ago
In the current environment where documentation can be automatically generated from the comments in your code, refusing to comment your code is just lazy, outdated practice. It’s like they’re out here still insisting on using their laserdisc player.
1
u/BinarySpike 17d ago
This depends entirely on the project architecture. An old piece of software using archaic methodologies is gonna need some hints at what's going on.
But put any self respecting C# dev in front of a C# project developed in the last 10 years using clean architecture and there's very little they won't recognize.
1
u/gd19770226 17d ago
In general I leave comments in code for two instances.
1.) One company I worked for had a few legacy functions that were extremely important and fragile. Everybody on the team hated working on these functions, and management wouldn't let us rewrite it into something less fragile. One ticket would often break something else. Somebody would remove code, and it would fix something for one customer, and break it for another. So we all got in the habit of leaving comments with the Jira ticket # and the reason whey a certain block needed to stay in place.
2.) I only did it a few times, but one guy on a team I worked for would leave comment place holders where code for a future ticket should be placed. This way the lower level programmer who took that future ticket would put the code where he wanted.
So I wouldn't say NO comments ever.
1
u/failsafe-author 17d ago
I swear by this. Most comments are not needed and make code more difficult to maintain. There are exceptions, especially at interface boundaries and when dealing with third-party libraries or business logic that is complex.
Overall, where you are tempted to write a comment, make a method instead. Break your code into small enough chunks that each method is easy to understand on its own, and comments are unnecessary and would just be redundant for what already exists. Once you’ve gotten to this point, retaining the comments means more work to keep in sync, and if you fail, means you’ve added more confusion to the code, making it less understandable.
I instruct our developers to go light on comments, but heavy on markdown files in repos that give high level overviews about the code and what it’s doing.
1
u/Far_Archer_4234 17d ago
Good code shouldn't need comments. 🤷♂️
If you disagree, then you probably aren't naming things well, or are writing assembly.
1
u/Calm-Medicine-3992 17d ago
Make code readable whenever possible. Don't use redundant comments that just say what the code obviously does either
1
u/spisplatta 17d ago edited 17d ago
It's a tricky subject, but in my highly personal opinion you should be cautious about adding too many comments. They should be about high level concepts and unintuitive things.
This is basically the ideal comment // For memory efficency we use the Mitsubashi algorithm to calculate the frobination coefficient which is then followed by 40 lines of dense algebra none of which has individual explnations, but each of which can easily be related back to the paper by Mitsubashi et al.
This is the worst type of comment a = b * c // Multiply b and c and assign it to a it's just noise and with too many comments like this it actually makes the code much harder to read.
This comment is neutral it doesn't add anything but it doesn't get in the way too much either. Adding such a comment that is itself useless to comply with a policy that all functions are commented is reasonable.
// Calculates the radius of a circle given the area
// area - the area of the circle
// returns the radius
double calculateCircleRadiusFromArea(double area)1
u/Complex-Magazine6690 17d ago
Comments are a tool like any other. If used well they can save an enormous amount of headache for people reading your code for the first time. If used poorly, they will misguide people. The biggest issue with them in my experience is that other engineers can (and often do) alter the behaviour of the code without updating the accompanying comments, leading to a drift between what the comments say is happening and what is actually happening. A wrong comment is so much worse than no comment at all.
1
u/AverageHot2647 17d ago
“good code shouldn’t need comments” is an oversimplification.
Most code does not need comments. Most code is not doing anything complicated or hard to understand.
Some code has a high essential complexity, and therefore benefits from comments explaining it.
A lot of code has a high accidental complexity, and people (wrongly) reach for comments to mitigate this.
Comments are not checked by any tooling, so they can be misleading, out of date, or just flat out wrong.
…
So, my recommendation is:
…
Add comments to API boundaries (many languages support doc comments which can be used to generate documentation, and using them is good practice).
Ask yourself, “am I adding a comment to mitigate against accidental complexity?” If so, first refactor the code to be less complex. Then ask yourself whether the code still needs comments.
If comments add nothing that isn’t already obvious from the code, then don’t add them.
1
u/ZeusTKP 17d ago
Like almost everything else in software engineering - it depends. There are tradeoffs.
No comments ever is almost certainly bad. Comments for every line of code is almost certainly bad.
It's an art.
You learn to recognize when the future reader will need a comment to explain the code vs reading it directly.
1
u/Ronin-s_Spirit 17d ago
"my code is self-documenting" type shit, that only works to an extent and some amount of comments is always needed.
1
u/xvillifyx 17d ago
I think bickering about comments is one of the biggest wastes of time
Put comments where you feel like you need them, and where they’re not likely to obsolesce
People overthink the fuck out of this for no reason. Surely your company isn’t hurting for disk
1
u/Luneriazz 17d ago
Good code should have comment. Something like
For jared, this method return string or int why? Fix this
1
u/Etsamaru 17d ago
I feel like really good code is readable without comments but comments are still super useful for explaining things.
1
u/ShroomOfGloom 17d ago
The truth is it takes skill to write maintainable code. And its very hard to teach. If its obvious from the signature of a function what it does, you dont need to follow it when reading call sites. If your functions are pure you dont need to worry about context or side effects. If your classes have a clear and well established scope and purpose they can be replaced and tested in isolation. The cost of calling a function is essentially 0 so you can use them not just for deduplication but for modulatization and documentation. The reason patterns work is because they communicate a clear intent to the reader. I can add a decorator because I want to separate the original class while also adding my own modifications on top. Thats the open-closed principle from SOLID. The decorator is a separate concern and I can use either the original or the decorated and I can reason and test them in isolation.
Clean code also prevents you from using it wrong, making the correct solution obvious.
To be fair, I spent maybe 10 years before I could write code thats easy to grok at a glance and only after struggling and reading a few books (the pragmatic programmer, gang of four, clean code, effective cpp and others). I've been doing this for over 20 years now and while I do write comments, I don't have to do it often. I read hundred of thousands of lines of code written by hundreds of people across multiple high level and low level languages. And yes, I understand my own code at a glance 1 year after I wrote it. Having 4 years of experience doesn't give the authority to dismiss advice you disagree with by calling it "the stupidest thing".
1
u/wholeWheatButterfly 17d ago
Often good variable names and helper functions can be easier to read than comments, especially when global design patterns such as immutability are maintained (immutability is just an example of a potential global design pattern in a project, not a prescription that immutability should always be a pattern).
And good design is more defensive than "why" comments in some scenarios. If function X must be called before Y, don't just call X then Y and leave a comment warning that X has to be called first. Write the code in such a way that Y cannot be called first, i.e. instead of both X and Y changing the class state directly, have X create an intermediate output that Y requires as input and change the class state after (just an example possibility). A comment explaining this might still be useful, but it's also impossible to ignore / miss without a larger code change. Whereas otherwise, X might get moved beyond Y accidentally at some point in the future and it could cause some difficult to trace bugs.
I think "comments are bad" isn't a great blanket opinion, but there should always be thought around "can better written code accomplish the understanding or warning that this comment is making?" And if the answer is yes (particularly if rewriting the code is low effort), then a rewrite is probably worth it.
1
u/craigs63 17d ago
Good comments should tell “why” and not just “what” is being done. The code probably only shows the latter.
1
u/uusrikas 17d ago
I don't use comments. Methods should be short and their names should communicate what they do. Comments are lazy design
1
u/Gznork26 17d ago
I’m retired now, but my process was to lay out the logic as pseudocode comments, and intersperse the actual code once I’d covered what was specced.
1
u/dnult 17d ago
As with all idioms in programming (or life), it depends. I personally believe in the use of meaningful comments that describe generally what a block is doing, or comments to describe obscure statements. In the other hand, comments should be too verbose, or else they get stale as the program evolves. The opposite extreme is a complete lack of comments, which can make it difficult to debug or refactor someone else's code.
1
u/Accomplished-Echo-64 17d ago
It relates to your skills; read the code first, not the comment. If you understand what the code is doing, you definitely don't need a comment.
Wait, uhhh, stop... did I write this as a comment for my code? The user says that if the code is understandable, I don't need to write a comment; if not, I should.
Wait, I'm writing the comment now. Do I need to write it?
→ More replies (1)2
1
u/Positive_Luck909 17d ago
Comments are helpful for humans reading the code.
Code doesn't need humans to read it.
1
u/Particular_Camel_631 17d ago
I strongly disagree.
If tte comment and the code are at variance then that is a strong signal to understand that part of the codebase better. Both what it does and what it should do.
In other words: it’s useful.
Don’t get rid of useful stuff! Explain what’s changed and why.
1
u/Mango-Fuel 17d ago
you definitely need some, just use them sparingly for important things; and make sure you can't convey the same information with better naming.
1
u/Blind_Chicken_24_7 17d ago edited 17d ago
I hated comments when I had to read and write them myself, because they were often out of sync. DRY basically used to apply to comments.
The reason is reading documentation, building a mental model, following down a rabbit hole and until you realize the comments essentially lied to you is pretty bad. This doesn't happen as often with llms since they do their changes quite diligently, so comments are good again!
1
u/minneyar 17d ago
That's what I expect to hear from somebody who doesn't know what comments are for.
You don't use comments to explain what your code is doing. That should be pretty obvious if the code is written well. You use comments to explain why you made the choices you did. Why is it organized in a particular way, why did you choose to use the algorithms you're using, what other options did you consider?
One of the worst things that can happen when you're reviewing some old code is to think, "This is dumb, why did they write it like this? I'll rewrite it and make it better," and then, after you've spent a few days rewriting code, testing it, fixing issues, and handling situations you didn't expect, you realize your implementation ended up being exactly like the old one.
1
u/jackandcherrycoke 17d ago
Comment liberally. No one knows how you think except you. Just because you find something obvious doesn't mean the next person will. Why make someone work harder to understand not just what you are trying to accomplish it but how you are trying to accomplish it.
1
u/-cosmicvisitor- 17d ago
Couldn't agree more, ignore the downvoters. Oh and I only have 20+ years using C++/Java in finance, so as a tech leader for some time now I make sure everyone understands this from the outset.
1
u/DrDam8584 17d ago
If your code can be totaly understood without any comments (each bloc of code are self-commented), why not.
But not every développer don't have this level, and sometimes, your logic are not "explainable" only by the code. Just the question "why did he made the process line this and not with another way".
In my team, I have an excellent dev, i love how it's code are, sometimes it's just "beautifull" to see it in the IDE. But when it's time to patch it or verify it, just a comment about "why did you use a strange bits manipulation here" is just mandator. There is many other way to code this logic, why this maner ?
1
u/markt- 17d ago
Biggest problem with comments is that they can lie.
Ideally, they shouldn’t. But they can. Ultimately the code is the only source of truth that you have, so the goal should be to write the code as clearly as possible, so that you do not have to depend on comments in the first place. At that point, writing the comment is largely redundant, and only needs to be exercised if there are some legitimate business reasons to do so.
1
u/Abject-Job7825 17d ago
You only need to annotate what other people aren't going to understand easily, it's true that good variable names and structure goes a long way but providing context is incredibly important too, especially since a lot of codebases use a lot of abstraction
1
u/s0ftware-dev 17d ago
If the code cannot be understood without comments then it’s shit code. Really is that simple.
1
u/boomkablamo 17d ago
Someone changes code and forgets to change comment. Or they do change it but its wrong. The comment becomes a bug if people take it at face value without looking at that code. If they have to look at the code, what's the point of the comment? This gets worse as number of developers working with it increases.
1
u/lazyegg31 17d ago
Have your seen AI generated comments before? Blocks of blocks of words sometimes longer than the code it explains. Those are the damn problem this saying is targeted. Like no I don't want to read essays in my fucking codebase, most developers read the code itself and they will be able to get a good grip of what it does, so "good code doesn't need comments"
1
u/markort147 17d ago
It doesn't mean that the code shouldn't actually need comments. It is just a hyperbolic way to say that the code must be clean and readable.
1
u/TryAgainbutt 17d ago
That's nonsense. Adding appropriate comments almost always helps someone understand the code. I've seen people overdo it and that's kind of annoying but not to difficult to ignore. Simple comments that explain the purpose of the operation. Also, segmenting code into smaller chunks that have a limited range of operation helps organization as well.
1
u/DamienTheUnbeliever 17d ago
Comments rot faster than code and it's almost like the compiler doesn't check them.
A good comment explains why. A bad comment repeats what the code says, poorly. But even good comments rot
1
u/OutrageousPair2300 17d ago
Comments quickly end up out of date and generally make code harder to read. Unless they're there for the sake of some tool that auto-generates API docs, or you have some especially opaque piece of code that can't be cleaned up for some reason, leave them out.
Important in the age of AI, they also don't help AI to write better code -- even though most AI models love writing extremely verbose comments.
What's infinitely better -- and does help AI write better code -- is to have your code be "self-documenting" which means to give functions/methods, classes, variables, etc. appropriate names that describe their purpose or functionality. Use appropriate types and classes whenever possible. Don't use "magic numbers" in your code, instead put those in constants defined with sensible names.
1
u/denbesten 17d ago
Good code shouldn't need comments to explain how it works. Comments that describe in natural language what it is doing, why it is being done, and that add context are often useful.
1
u/mxldevs 17d ago
If they've never needed to comment their code either the problems they're solving are too simple or the complexity has been moved elsewhere
Very often you will see code written a specific way and it's clear what it accomplishes, but it's definitely not clear why it's being done in the first place.
1
u/oldendude 17d ago
There are different kinds of comments:
Concepts
Documentation of public interfaces
Explaining something tricky
Noise
#1 is essential to understanding some code. I don't think it's necessary for a CRUD application, for example. But if code is implementing an algorithm or part of an architecture that isn't well known, some explanation is warranted, perhaps as simple as a pointer to a document.
#2 is not controversial, I think.
#3 is useful to help readers understand detailed logic with subtlety. The need for such a comment may be a sign that the code is too complicated. But often, you have some code that is clever, or non-obvious in some other way, and a comment is useful.
#4 is dumb documentation, e.g "a +=1 # Increment a by 1". You can safely assume that someone reading your code understands language constructs, for example.
The division between #3 and #4 can be a fine line. For example, if I have an if/else, I'll sometimes include a comment before each block, explaining the case each block handles. I'm describing the blocks in terms of the algorithm (for example), while the if expression might be written in lower-level terms. That *might* indicate that my code can be improved, so that the comment is unnecessary.
I think that OPs title "good code shouldn't need comments" is basically right. You want to have your code be clear enough -- through structuring, variable naming, etc., so that it is obvious what the code is doing.
1
u/Separate_Newt7313 17d ago
I like my comments how I like seasoning on my food: Not too much. Not too little. Bad seasoning/comments can make the whole thing much harder to get through.
In the debate of whether good code needs comments, I would say: Yeah, sometimes it does.
Sometimes:
the language makes things hard or awkward to express cleanly
the syntax is really ugly
the solution is not readily evident
I'm new to a particular language or concept and the comments act as a handrail for my thoughts
Last thought: Humans invented programming languages as a form of unambiguous communication with dual purpose:
to be read, understood, and modified by humans
to be convertable into a machine executable format
1
u/ShelLuser42 17d ago
However, I may be wrong. What do other people think, do yall like code with minimal comments, what are the benefits of writing it that way?
Coding a project is one part, designing your project; now that's a whole different ballgame. There's a good reason why I'm quite the advocate for UML and why I absolutely love the PlantUML open source project.
The reason I mention this is because a lot of people also don't see the value in this approach either, and yet there are many big projects which have been (forcefully) rewritten from the ground up because of design issues that crept in over time.
Same with commenting.
Heck, depending on your choice of language it could easily become a bit of a must-have. I mean, a Python module without proper docstrings (= comments?) is pretty much useless because without it it'll get very awkward to find out what it's supposed to do and how you're supposed to use it.
1
u/RageFucker_ 17d ago edited 17d ago
I don't like that statement because I feel like it oversimplifies it. Some code is going to be complex and comments can be helpful.
Here are the rules I follow:
Use descriptive names for functions and variables.
Add concise comments to give the next dev a good idea of what is supposed to be happening. I do this for sections that are complex.
Any time you update the code, update the comments as well. Same goes for design docs.
Keep functions as small as possible. Same goes for lambdas. If you need more than about 10 lines of code in a lambda, turn it into a function instead. This improves readability and maintainability.
I know some people will claim that comments are never necessary if you code correctly, but that's not true in my experience.
I have 21 YOE (C++) and I've only ever worked in codebases that are 20-30 years old, so I'm constantly coming across code that is hard to understand and maintain. I know the frustration of trying to do that, so I tend to leave comments for the next dev since it's not always feasible to rewrite large subsystems or sections of code.
For example, I currently work for Microsoft and I've been in my current codebase for over 5 years. I've come across 2,000 line functions and 20,000 line .cpp files. I don't have time to rewrite stuff like that. I try to reorganize when I can to improve readability and maintainability, but it's not always possible.
1
1
u/teetaps 17d ago
I’m not a traditionally trained software engineer, so my opinion is here for anyone who has imposter syndrome around writing software.
I love notebooks, because they let you write more prose than code and as someone who is bad at code, prose helps me think.
There are lots of arguments about notebooks that we can get into if you’re interested, but for me, notebooks help me write better code because I can get the bullshit out in human words, and save the good code for code blocks.
This obviously applies best to data science, but notebooks can be used for serious software dev to an extent, in my experience.
And in any case, the mental model most of us carry is that a script is regular code decorated with comments. In my work, a notebook is comments decorated with code. They both run with Python, they both can be managed by virtual environments, they both scale with the abilities of the programmer, so.. what’s the big deal? Yeah Jupyter sucks but today there are better frameworks like Quarto and Marimo that preserve plaintext so they’re version control friendly, it’s just that where other people start with a .py, I start with a .qmd. My “code” just has significantly more human writing that describes what I wanna do in great detail and then does it in a code chunk.
“Good code doesn’t need documentation”? Maybe for robots. But I’m not a robot. I’m a human with a squishy brain between my ears. I would rather read a book about complicated code and come across the code in bits and pieces, than read a bunch of code that I don’t understand and have to find explanatory comments.
1
u/slashdotbin 17d ago
I work with schedulers in infrastructure. The first version I was onboarded to when I joined my current job was beautifully written code and I appreciated how good it was. Learnt a lot from it overtime.
If there were no comments I wouldn’t have understood anything. It would have taken me atleast double the time to understand the very basics of it.
Comments are very helpful.
1
u/y0shii3 17d ago edited 17d ago
Code is more honest than comments; incorrect code will often cause a crash or a compilation failure, but incorrect comments just sit there continuing to misinform until someone takes the time to actually read and question them. So, it's better to try and make your code self-explanatory than to leave the bulk of explanation to comments. Also, when you update your code, the more comments it has, the more you have to check and possibly edit, so self-explanatory code reduces the amount of stuff that you have to edit on each change. That's what we're really trying to say when we tell people "good code shouldn't need comments." Obviously, there's limits to how self-explanatory your code can be, and even comments which redundantly explain things that can be immediately gathered by glancing into a function body are still good for auto-documentation tools, so don't take "good code shouldn't need comments" too literally.
1
u/Jon_Hanson 17d ago
Comments should describe why you’re doing what you’re doing, not what. Any competent person can read the code and see what it’s doing.
1
u/NewInflation2121 17d ago
Rule of thumb is to use comments if the code is not self-explanatory.
The downside of comments is that you have to maintain them, so they may be out of date or miscommunicate things and there are no compile time checks to see if they still make sense after refactors.
If you have only been coding for 4 years, you may not have fully realized what elegant code looks like yet or how distracting visual noise can be when you are trying to understand the logic.
Consider this: If you need to write a comment to explain what your function is doing, then maybe you haven't named the function correctly or your function is taking on too much responsibility. They are usually indicators to how well the code is engineered.
What is very frustrating for senior devs is looking through a function that has comments explaining that you are looping through an array or assigning variables... It's redundant and distracting.
2
u/Due_Manager_7987 17d ago
The downside of comments is that rather than cleaning up the code to make it self-explanatory, you end up with dirty code and an explanation. You have to read twice as much and it’s harder to read.
1
u/Ok-Craft4844 17d ago
I have, actually. Be it because the comment didn't add anything to my understanding (classic: method void foo(Bar bar), javadoc "foos the bar"), be it because the comment lied.
I love high level comments, like "how does this all go together" or "what is this module supposed to contain". For individual parts, I've seen few cases where lots of comments wouldn't be better invested in better abstraction and more ideomatic usage of the actual language
1
u/Adorable-Strangerx 17d ago
Comments for explaining why not what. If you code needs explaining what it does you have shitty code
1
u/guywithknife 17d ago edited 17d ago
It’s bullshit.
“Self documenting code” also doesn’t actually exist. So called self documenting code rarely does. It’s what people who have never had to maintain code over a long period of time call their bad slop code because they’re too lazy to document it.
It doesn’t matter how well your functions and variables are named, unless your functions are trivial, they’re not going to explain the intent behind the code.
Comments should say why, not how. Sometimes what, rarely how. The code already tells you how.
That doesn’t mean you need 50 lines of comments for every 2 lines of code. A lot of code doesn’t need comments, but when you do need to explain why some code exists or does it the way it does, don’t be shy about using comments.
→ More replies (16)2
u/TheLurkingMenace 17d ago
Exactly. I don't write comments so I know WHAT the function does, I write them so I know WHY the function exists.
1
u/redditNLD 17d ago
I want to see one line above any function that's over like 10 lines, and maybe one at the top of the file that quickly says why that file exists. That's about it and just so I can read less.
1
u/Relevant-Register-69 17d ago
Sorry but you're wrong.
First, think about the added maintenance burden of updating the code, and then also making sure that every comment is up to date.
Next - I'm not reviewing the idea of how something should work, I'm trying to figure out if what you built does what it should do. I can't verify this from a comment. Therefore, it must be obvious what's going on in a scope that is easy to fit in my head
A pattern I've observed over and over with LLMs is comments about implicit details of a function based on the behavior of other functions, for example "an execution on path xyz will never reach this branch because it's gated by functionName". This is awful for all the stated reasons above - the comment might not be true in a week, it tries to make up for a complex design with comments and it requires me to pull in additional context from elsewhere (and btw this is also indicative of bad design)
1
u/JohnCasey3306 17d ago
I'm sure it's possible, but only true for 1 in every 100 of you who genuinely think so of their own code ... The other 99 -- no, your code is shit and you lack self-awareness. So do comments.
1
u/Musikapparaten 17d ago
Good self explaining code might not need it but it do not get worse of it. The problem with comments is that you have to write and maintain them. So in that sense it’s better to document the code that might not self explanatory. Good code, as in nicely written etc can still be hard to wrap your head around.
1
u/d4rkwing 17d ago
It depends on the type of comments.
Comments that give a high level overview are useful.
Comments that explain work-arounds for known bugs in hardware or 3rd party libraries are useful.
Comments that say “add two numbers” are completely useless add negative value.
1
u/Simengie
17d ago
•
Even with what most companies would call excessive comments we have code sections that need more. After 25 years you just forget stuff and new people go WTF. We have a math formula that did not exist before a math specialist developed it for us. the comment explaining what it does and how to read it is 300 lines long. The code for it 30 lines. I still have the 20 page document the math guru wrote as the proof for it. Without that those 300 lines of comments just feel lacking. But we felt 300 lines was the limit of trying to explain it in comments.
Never too many comments.
1
u/Simengie 17d ago
I am seeing a bunch of people argue against comments that has never had to do design reviews where one of the deliverables to a customer is function frameworks that are all comments that will be built out later.
May be outdated in some fields but others it is still required.
Also if you do software for any medical device that works on the inside of persons body ever line must be commented fully. At least it was last time I talked to my friend that was working on the next generation artificial heart.
Don't complain about maintaining comments. Its your job as part of software maintenance.
1
u/therealbergerle 17d ago
A colleague of mine always said, comments are just deodorant for smelly code. And I think for the most part he’s right. Well written code rarely requires comments. I only use them in special cases, e.g. if something intuitively looks wrong but is actually just a stupid business requirement or to explain why something non-obvious is happening.
1
u/nekoeuge 17d ago
Some comments are needed. However… First, comment should say something that’s not already said in the code. Repeating code in comments is bad, because copypaste. Second, before writing a comment, ask yourself whether this comment could have been a code. Comment that is used instead of code refactoring is bad, because code is intrinsically more reliable than comments, thus it’s preferable.
Only the comments that are not obvious from any possible code are worth to be written.
1
u/MagikarpPatronus 17d ago
When comments become out of date due to updates in the code, it is worse than having no comments at all.
Over-commenting is a problem because it adds maintenance cost to the code that can sometimes exceed the benefit it provides. Comments need to be updated when they become outdated, and your compiler/interpreter can't help you find out-of-date comments.
That doesn't mean comments are bad, but you should take into account maintenance risks and costs when writing your code.
Some commenters have suggested documenting purpose, why, et cetera in comments. This is often a good option: a lot of the time, this type of documentation is less likely to change, since it doesn't change every time the code does. And the lack of redundancy tends to make those comments more helpful.
You should also learn from those self-documenting advocates, not because their position is the appropriate choice in all situations, but because they will offer you alternatives that in many situations could help you avoid having to maintain comments.
Finally, another code choice to consider is to move comments/documentation to your tests. It's easier to keep this documentation up to date, since it's tied directly to the test verifying the behavior.
1
u/Vesuvius079 17d ago
Did I get sent back in time? Is it not 2026 anymore?
Anyways, my previous opinion on the topic of code comments is that they should explain the reasons the code exists when it’s not obvious or the reason the code is weird.
They are not helpful if they explain what the code is doing when that is obvious from the start.
None of this matters anymore though. What really matters now is whether AI needs comments. I think it tends to do better with design docs and specs as reference material but it does leave verbose comments on much of the code it generates.
1
u/jeffbell 17d ago
I wouldn’t say never.
If you are using a particular algorithm it sure is helpful to comment which one it is rather than expecting the reader to recognize it.
I do find that picking good names for methods and variables can certainly reduce the need for comments.
1
u/gulf_of_sanity 17d ago
comments shouldn’t explain what code does, unless your code is WAY too “elegant”, comments should explain WHY your code is doing something
example:
#always convert string to lowercase because foreign API doesn’t like capital letters
1
u/gwenbeth 17d ago
As previously stated comments explain why. Here are some examples:
// We need to handle nulls in this data even though this is against the spec because there are credit card terminals that send nulls instead of spaces.
this regsub is changing a normal hyphen to a non breaking hyphen so our build IDs don't get split between two lines in this table
Write comments remembering that in 6 months when you look at this code again you won't remember what you did.
1
u/Linaran 17d ago
Comments go stale and never get updated. They quickly become noise and sometimes an excuse to fail at providing good symbol names.
Good self documenting code doesn't need comments.
That said if the underlying domain is truly complex and I'm looking at class that represents certain complexity, a few words describing what it represents is nice.
But if you find yourself writing paragraphs regularly then it's a noisy bad habit.
1
u/ZucchiniMaleficent21 17d ago
Code says what it *does* (assuming the damn compiler doesn’t screw up, which has been known).
What it does *not* say is what it is *meant* to do. And Y’know what? It’s amazing how often the two are not the same.
1
u/tgm4mop 16d ago edited 16d ago
There's no universal rule for comments. It depends on who's going to be reading the code, how complicated it is, and how a comment can help human understanding. Think about what you yourself would like to have explained if you revisit the code a year from now.
Some reasons not to comment:
* If the comment adds no information that isn't easily seen in the code
* If the comment can easily get out of sync with the code
* If the comment would be unnecessary if you used a better variable name or an assertion
Some reasons to comment:
* Documenting public APIs. People should not need to look at private implementation details to learn what public APIs do.
* Explaining or citing sources for more difficult/nonstandard algo and data structure implementations.
* Citing external spec documents. Eg. "These constants must match RFC 1234 section XYZ"
* Explaining unusual, "smelly", or hacky stuff. If someone would look at the code and think "this looks wrong" or "wtf", then an explanation is appropriate. Eg "Size is doubled to offset a bug in LibXYZ's buffer sizing"
* Documenting implicit behavior or requirements. It's best to make stuff explicit, but it's not always possible. Use comments if you can't make the code explicit. Eg. "This function must run in constant time to prevent side channel attacks"
1
u/PvtRoom 16d ago
unless your code contains enough info to:
produce a help file,including dependencies, what depends on it, where it fits in, what inputs it's takes, what inputs it requires, ay structures it relates to (eg guis or com servers or whatever) and how to use it, and its requirements, it's not self documenting.
1
u/Specialist_Chart3519 16d ago
Since I am generally the only person who sees my code, with the exception being the few things I've shared on github, I do not comment a lot, but I do try to make my function names, variable names, parameter names, etc very obvious even if it means typing a longer name.
That being said, sometimes I run into occasions when I pick back up on a project and have to spend way too long figuring out what something was for, even with hyper specific names and the few coments I left. I'll admit, it's probably due to my skill level of coding, but it leads me to believe more comments is never a bad thing.
1
u/AsianAnomal 16d ago
Good comments help clarify non optimal code. Which can happen a lot under time pressure.
When doing 3D math its always helpful to explain with comments what and why youre doing something.
When writing APIs comments help explain what each parameter does without having your user needing to read into your code.
1
u/Straamannen 16d ago
Good code doesn't need comments to tell you what it does.
You still need comments to tell the reader why it's doing what it's doing.
Our Swedish counterparts are insane and treat a failed action as fine and just return the structure with a few missing pieces of information, hence we need to check for those here and retry if they are missing. DO NOT FUCK WITH THIS.
Translated to English, but it's a piece of code I've seen, and without it I might have considered the check ridiculous defensive programming.
1
u/ohcrocsle 16d ago
The only times I've wished code was commented was when the original commit was implementing a polygon intersection detection algorithm and I had no idea what it was called or how to figure out if there was a problem with the implementation. I mean, I knew there was a problem because it stack overflowed with a specific polygon, but you get the point. It took me a day to sift through available algorithms and figure out which one it was. Otherwise, I'm a believer that comments are usually a distraction and maintenance overhead and it's better to just read the code.
I remember wishing people didn't use LINQ when I started because it was very difficult to understand. After a while, I understood the language of LINQ and realized it was my skill issue.
1
u/Powerful-Joke5120 16d ago
So many unnecessary generalizations. Code and comments are two separate things. Often the most efficient code is written using specific techniques that aren’t even intuitive if you’re unfamiliar with the code. Comments are there just to help the next guy who has to deal with whatever is going on.
1
u/mikekchar 16d ago
I haven't read the comments, but since I'm very opinionated on the topic:
Good code doesn't need comments. When you write comments, from a linguistic point of view you are "code switching". Ideally, when you communicate in a language you use that language to communicate. When you find that you are reaching for your native language to fill in the blanks, this is sub-optimal. In human languages, it's called "code switching".
Programming languagues are languages. Some people feel that it is impossible to communicate the full intent of your code in that programming language. I don't think that is generally true. There are no people whose native language is a programming language. That would be stupid. There is obviously a lack of expression in a programming language. However 90+% of the cases where people say they can't express their intent with the programming language it's because they simply aren't fluent enough in the language.
HOWEVER... None of that fucking matters. If you are not able to express yourself in the programming language, avoiding writing comments is just shooting yourself in the foot.
Every time you notice, "Hey, I can't express myself fully here in the programming language", you should consider that as an area where you can improve. You should improve. Not improving means you are a bad programmer. Being exceptionally fluent and being able to express your intent in a programming language is something that requires years and years of experience. If you give up because you can just write comments, you are losing a lot.
But for now it doesn't matter. Write the fucking comments. Second best is better than last best (doing nothing). Work in the future to try to get to a point where you can adequately express yourself without resorting to your native language. But in the mean time, express yourself any way you can.
→ More replies (12)
1
u/LegalPie5881 16d ago
It’s not the same but I revisited some old scripts I wrote over a decade ago and while I did have some comments a lot of the more recent stuff I’d written used techniques and code styles that I’d just learned so reading it now was getting super confusing. I love comments.
1
1
u/KiwasiGames 16d ago
> explain every function in a one or two line description
Functions change over time. Comments don’t.
A massive issue I’ve had working with legacy code bases is figuring out who is actually right. This line checks if the temperature is above 50, but the comment says it checks if the temperature is above 30. Now I have to parse two competing models of what the code is supposed to do.
Write your comments assuming they will never get updated.
1
u/aspbix 16d ago
As a person with ADHD and is overwhelmed by cluttered codes, I realistically work best with adding comments when I resume working on a project where I tend to forget certain features/functions.
However I usually have the habit of skipping comments in my code because I thought I would have it all sorted out for when I came back next session. In reality, some of it remain unorganized I have to clean it sometimes.
1
1
1
u/MpVpRb 16d ago
Partly true
Clear logic and well thought out, consistent function and variable names eliminate the need for many comments.
Explaining tricky constructions or reasons for a particular approach is still good.
The biggest problem with comments is that they get out of sync. Write code and a comment. Some time later change the code and not the comment. Obsolete comments are worse than useless, they can be very confusing and dangerous.
1
u/eyes-are-fading-blue 16d ago
Comment outside of hacks and unexpected behavior or otherwise unusual piece of code is noise. These should appear seldomly and therefore seldom comments outside of customer facing public APIs.
1
u/Alarmed-Plant8547 16d ago
The code should tell you what's happening. The comments should tell you why.
1
u/goomyman 16d ago
Rather than add a comment - name the variables and methods appropriately.
Comments can be misleading and don’t have a compiler verifying them.
You can refactor a variable name to something else - it doesn’t change the comments. Comments can get out of sync.
Not saying don’t add comments - it’s just they are most useful when it’s something complicated.
With AI tools now, I feel like comments are more important since AI will update comments and people aren’t writing code by hand. It’s useful for code reviews and understanding.
1
u/Katieg_jitsu 16d ago
I over comment most explaining what the code does or what j meant it to do maybe a brief why and then code review might catch if a change in code changes the intention
1
u/PipingSnail 16d ago
Code that has no comments is a disaster. The comments provide the explanation for what we are trying to fo and why. Occassionslly there will be a how because sometimes the approach chosen is not the obvious approach snd there is a reason for that.
Comments also document your sources for stuff that is officially undocumented (I write code that relies on understanding Windows internals, much if which MS do not provide official documentation for).
Lastlyccomments document where API calls you make deal with bugs in the API (the API behaviour deviates from the documentation if you've worked with Windows long enough you've seen a few of these edge cases).
Anyone that tells you that good software is self documenting is talking out of their ass, bor has never had to work with a team, or with their own code for an extended period of time. Some our code is 24 years old, and I remember nothing about the thought processes when it was written by me, but the comments do all the heavy lifting.
1
u/solarmist 16d ago
Comments should never describe what you’re doing that’s literally the purpose of code, unless it’s incredibly convoluted. But they should be used liberally to describe why.
1
u/rainbowWar 16d ago
Good code needs comments, but it is much better to aim for self-documenting code as a goal.
Self-documenting code mean using clear names clear workflows, clean code. If you do that then you shouldn't need ot comment much.
Comments then are only for explaining the reason you are doing something, not what you are doing.
1
u/infinity_o 16d ago
Good code doesn’t (usually) need comments about what it does, but it often does need comments about why it’s doing what is it.
1
u/TestSubject006 16d ago
I've been writing a lot of collision and physics code recently. There's no way I can expect people to just sight read the geometric intuitions and just get how it works. I wrote it after weeks of reading papers, and I can't follow it all that well.
1
u/new-runningmn9 16d ago
My rule of thumb is that code already explains what I am doing, the comments are to explain WHY I'm doing it. In any modern IDE, comments aren't really distracting anymore. Be kind to those that follow that may not know what you know when you first wrote something. At least half the time, you will be the one that follows, and you won't remember.
1
u/skamansam 15d ago edited 15d ago
I am going to oversimplify this to be as brief as I can. I have taught many Jr devs what this means using similar examples.
/* calcalate the sum of the primes of each weekday
*/
function weekdaySum(d){
let c = [1, 3, 5, 7, 11, 13, 17, 19]; // first 8 primes, +1 for errors
let a = 0; // starting number
let b = 7; // days of week
// we add primes so the days don't collide
for (int z; z <= d; z++) {
a = a + c[z] || 0;
}
return a; // return the sum
}
/* We have a legacy system that stores Days as ints in
* such a a way that the sums will never collide, in mush
* the same way that permissions in *nix systems work.
* This is used to bridge the gap from the legacy system
* to our more modern one. a 76 (sum of first 8 primes) return means something
* went wrong.
*/
function calculatePrimeSumForDayOfWeek(dayOfWeek){
const arrayOfPrimes = [1, 3, 5, 7, 11, 13, 17];
let primeSum = 0;
const numberOfDaysInWeek = 7;
const errorCode = 76;
if (dayOfWeek > numberOfDaysInWeek) return errorCode;
for (int dayNum = 0; dayNum <= dayInWeek; dayNum++) {
primeSum = primeSum + arrayOfPrimes[dayNum];
}
return primeSum ;
}
The first example is difficult to read and you need comments to understand what is going on. In the second example, the comments state WHY you do this, and the function itself uses good variable names and programming to let you know what is going on. For instance, the names actually say what they are so you don't NEED comments on them. The names fit into the name of the function so you know what role each plays. (primeSum and dayOfWeek in calculatePrimeSumForDayOfWeek.)The variable specifiers (const, let) are given properly to give you more context about HOW they are used.
In summary, comments should answer the question WHY, and your code should answer HOW, WHAT, and tracing back should give you WHEN. This is what it means to have self-documenting code.
1
u/Healthy_Bug7977 15d ago
Good code should need as little comments as possible. If you want to comment try to find a way to communicate through variable names or the like if applicable. If that doesn't work then comment.
Obviously no comments at all is stupid. It's just that some CS curricula are over insistent on commenting the most obvious things. That leads to people overreacting when answering.
1
u/Capital_Distance545 15d ago
Yes good code should document itself.
Comments only needed when you must do some counter intuitive thing, usually because of something outside of your control, like 3rd party behavior, requirements that does not make sense etc... and for those, you should try to first find better and more elegant solution, like changing the lib you use, or discuss the requirements again. And only add the very non trivial coutner intuitive code with comments when absolutely necessary.
You should always code in a way so that any newcomer, or even your future self will understand the code easily and see the correctness and cohesiveness easily.
1
u/UUDDLRLRBadAlchemy 15d ago
The code explains "what it does". Adding a comment that explains the same looks silly and shows everyone you're new. You're going to cringe at those a week later.
Comments are useful for explaining why.
1
u/FatDog69 15d ago
This comment is from lazy developers or managers who don't want time lines to increase because of documentation.
Comments should document the "Design" not the Implementation. Anybody can read the code to see 'what' the code is doing. But reading the code does not tell you 'why' the code is doing something at this location.
I have written 'what' the code is doing at the higher levels so the next developer does not have to dive into 3-5 separate files to trace the code.
Example:
Call a routine that will error check the rows of data, filter out bad rows then pre-clean any existing rows from the final table, then insert now new rows into the final table.
If the next developer has to suddenly go add code to fix raw data problems - this code tells him where to dive into to add new error checks.
1
u/Puzzleheaded-Joke780 15d ago
I comment my leet code aka. performance hacks, rest is obvious enough. LLM makes the docu and description afterwards
1
u/Significant_Ant3783 15d ago
If your variable names and constructs are obvious enough, you don't need to explain what you are doing. But always provide some context for every method.
If your methods are longer than a paragraph, you are doing it wrong.
If your methods are over 500 lines, go sit in the corner.
1
u/mireigi 15d ago
Good code should be self-documenting, meaning it shouldn't need comments.
E.g.
public SendEmailOutcome SendWelcomeEmail(User user)
{
}Just reading the signature of the method/function you can quickly deduce what it does, what it expects as input, and what it returns.
Whereas a similar method, implemented poorly, doesn't tell you anything about what it does, what a successful outcome looks like, or what the possible error states/codes are.
public void Process(string name, string email)
{
}Comments should, ideally, only be added, when there's a break from convention, or a decision was made during implementation that won't be obvious 6 months from now, when someone has to maintain the code.
public SendEmailOutcome SendWelcomeEmail(User user)
{
// Legacy system is still in use. To keep welcome emails consistent, we load
// the old template file, which business changes for holidays.
// When the legacy system is shut down, we will migrate welcome emails entirely to
// the EmailTemplate component instead.
var emailTemplateFile = File.OpenRead("welcome_email.htm");
var emailTemplate = emailTemplateFile.ReadToEnd();
emailTemplate = emailTemplate.Replace("[@userName]", user.Name);
this.emailServer.Send(emailTemplate, user.Email);
}Without that comment, someone might refactor the method/function, and break a promise made with the business (that welcome emails stay consistent).
1
u/wage_zombie 15d ago
I always prefer more comments to less. Some people use the "good code shouldn't need comments" to justify their own laziness. What is ironic is they typically don't write good code so they DO need comments.
1
u/theacp127 15d ago
I think even well written code needs comments. Codebases for any medium to large project have too much information for any one person to memorize all of and often people leaving and joining projects.
The person who wrote the code will eventually not be the person who has to maintain the code and the maintainer shouldn't have to guess what the code does months or years after it was written. Especially if it comes to things like handling edge cases, the code itself might be well written, but the reason it exists might not be as obvious to someone not familiar with the project.
1
u/Acceptable_Handle_2 14d ago
Yes good code doesn't strictly need comments.
But also comments help get others up to speed more quickly, even in good code.
1
u/AvogadrosOtherNumber 14d ago
Don't comment the code unless you need to. Comment the reason the code exists:
Wrong:
// if b divides with a zero remainder
if (a%b == 0) ...
Right:
// if no remainder run this block because otherwise the piston stops.
if (a%b == 0) ...
1
u/Dazzling_Music_2411 14d ago
Good commenting is indispensable.
Sometimes, if you need to explain/justify a coding choice, comments might easily be 10x more than the code itself. Leave them out and someone will subsequently say "why TF did they do it like this?" even if your code is crystal clear.
1
u/KevinJRussell 14d ago
That's one of those Robert C Martin style rules that is obviously true in simple cases, and blatantly false in difficult ones. In other words, it's a worthless rule.
A lot of rules end up like that. It's like DRY. In an ideal situation, you'll never have to repeat yourself. But in the real world, you have to do it all the time. Not everything should be abstracted. Sometimes programming is just hard, and it's a non-ideal environment where you have to do non-ideal things.
If all the code you've ever written was self-documenting, you're a garbage programmer who's never had to do anything difficult.
1
u/Grandviewsurfer 14d ago
So I have to read your comment to learn what you think the code is doing.. and then separately read the code to learn what it is actually doing? No thanks.
→ More replies (2)
1
u/FlossurBunz 13d ago
I've heard that "Good code is self-documenting". I don't think that means good code should never need comments, it means good code should be straight-forward and readable. Comments regarding decisions and invisible assumptions are still needed.
23
u/ralphpotato 17d ago
Comments can be wrong. Barring some interpreter or compiler bugs, the code does what is written.
My rule of thumb is that comments should explain why, not how. It’s good to explain why a decision was made, why an algorithm was used, why a variable needs to exist, etc. It’s really rare that you should include comments like, “loop over the array”. I think this is a lot easier said than done, and it’s hard to know what comments will be useful to someone else or yourself in the future until you actually go back and cross-examine that code.
I think I tend to under-comment my personal code and regret it later, mostly because I look back and I forgot my thought process. With code that you work on with others I think it’s generally good to comment at least at the function declaration/definition, class/struct definition, stuff like that.
Public APIs should be extremely well documented, and are beyond the scope of normal commenting style.