189 points · by ternaryoperator · 3y ago · 346 comments
I agree that comments explaining 'what' is happening are mostly useless. Write clearer code. But 'why' comments are good. Most things can be coded up different ways. Tell me why you chose this way. Tell me about constraints that might not be immediately obvious. Let me know if indeed, it could be cleaner, but you were in a hurry (this is a thing that happens in the real world), or if it's that way for a specific reason.
In my practice I often see code where useful comments are missing and hours of research required to learn something author for sure knew. Code which has too much comments to me is an imaginary problem - I've seen it at most a couple times in my career and one of them was the code written by a junior developer in a style one can expect in a tutorial or a book. But usually people quickly learn to not add unnecessary comments (and eventually start adding too little of them).
This is true, but if you just get these same people to write more comments, they will also think their comments are clear when they're, in fact, not. I think anyone who is capable of writing clear comments is also equally capable of writing clear code.
If I was to suggest investing time in learning some skill, I would suggest learning how to make your code actually clear by getting the right people (with relevant domain expertise, but without experience with the code) to critique it for clarity rather than learning how to make your comments actually clear.
Why questions are best answered in architecture documentation, the code itself should be self explanatory (given the architecture documentation) for the most part with specific why comments carefully placed in places where it doesn't make sense to use the architecture documentation.
I've read code from various codebases from various companies, large and small. I very rarely see a comment which is genuinely both well placed and useful. From the bits of the linux kernel that I have worked on, I have generally seen pretty good why comments, although I think a lot of them could be shifted into architecture documentation.
All in all, when reading code, my default stance is to ignore comments unless I get lost reading the code, then I attempt to read the comments. It has been incredibly rare that I've found unclear code to have clear comments.
Your experience is different than mine: I write software which interacts with cloud (Amazon AWS, Google Compute Platform, VMware vSphere), and a well-placed comment describing the quirks of whatever platform I'm working with helps immeasurably, e.g.
> VMware NSX will throttle us with an HTTP Status 429 "Too Many Requests" if > 100 API calls/second. In that case, we back off and retry rather than fail.
Think of it more like two lines of bearing. You are far more likely to get an accurate position from two lines of bearing. If you need to understand what past self was thinking, a comment is written in a different mindset than the code. Two different lines of reasoning.
Also, I rarely think about writing code for someone else. I write for my future self. And I really want my future self to like my past self. So I strive for clean code and write detailed comments, complete with references.
Imo, first, they are two different skills. And second, sometimes it is easy to write down what I am trying to achieve, but hard to achieve it with clear code. And other times it is vice versa - easy to write the code and hard to put it into words.
A long time ago, I had a tendency to write comments to explain code that could be simplified. Refactoring it usually made the comments redundant.
Comments are still very useful when the why is unclear.
Java example: rewriting non-stream collections code to use lots of chained streams. Using lambda functions when not needed. Rewriting case labels to use case lambdas. etc.
That sounds like a nice story
Teaching people how to comment is a skill that's just as important and nothing turns me off a project faster than the "code is its own documentation" mantra.
function Add(int a, int b) { return a - b; }
Code can lie in so, so many ways that are much more obscure and confusing than this simple example.Every time I see 0 comment in complex logic I attribute it to laziness of coder. And of course every time excuse is the same - its self-documenting, you see what its doing etc. But why, what are the effects elsewhere in the system and outside, what part of business needs this is covering, what SLA it tries to cover, what are overall goals etc. can be even impossible to grok from just code itself. World is bigger than just code.
pi = 3Code doesn't tell the full story either. And code can contain bugs so one cannot fully trust the code too.
If code/comments are out of sync it is likely that someone changed the code and forgot to update comments (which is possible to verify using VCS logs) or it may be that the comment stated the intention right but the code has a bug. Code+comments like a parity check to me - if they agree it is good, if not - I have to investigate if the comment or the code is correct.
Better not write tests either, because those will become stale too.
And any sort of user documentation/support/etc. It'll all just become stale.
It's almost as if code is just part of a larger 'thing' that has to be maintained.
Comments transition from truth to lie without any indication.
Tests represent truth in the same way code represents truth. In many ways the tests represent truth more than the code represents truth. Tests state "this is what I want" and then interrogate the code to verify that the code itself does what I want.
Tests by definition can not be stale (unless they are never called).
The ruby community is where I first learned about test driven development which is philosophically the idea that tests are the highest level of semantic importance.
There are DSL's in ruby land for writing tests like you might write comments: https://semaphoreci.com/community/tutorials/getting-started-...
If tests describe what you want, and code describes how it happens, then the major piece left is why it is the way it is, which almost everyone in this thread agrees is the most important thing to comment.
(I'm not arguing against writing comments though - the 'they'll get stale' thing is not enough to make them not valuable)
Unit tests are easier to maintain when incorporated to a CI/CD pipeline. Then every pushed commit (or Merge Request) will trigger the test suite to run and in case one of the tests fails the team will know.
They do go stale, but tests were invented exactly so that your documentation is able to alert you when it has gone stale. Their existence rests on being an attempt to solve to this problem.
There is an argument about reducing the amount of work.
On the staleness of comments, it's a real thing. In particular, on comments explaining design decisions, they will often touch on aspects of the system that are outside of the specific method they are attached to, and nobody will go back to them to rewrite all that prose.
We had a project with a ton of documentation written in the first 2 years, and as engineer count grew, these comments just disappeared as again and again they were causing misunderstandings, and actual documentation was already written in the internal wiki as each refactorings and new features were discussed and designed.
It's not just a rails thing, and after a while people stop trusting comments altogether, which make updating them a chore more than anything.
I think that's a reasonable approach if it's easy to find the relevant section of the wiki that describes the code you're looking at by searching. Or just have a comment in the code that points to the wiki. The important thing is to document the "why's".
The 5 programming languages with the least amount of bugs are:
Haskell
Ada
Scala
Rust
*Drum roll please* Ruby
Ruby is nothing like the other languages above in design, but that community has fantastic conventions around code clarity, code quality, testing, continuous integration, etc.Comments are for things like, `Todos`, Noting a specific algorithm, maybe a link to a white paper, noting a violation of a convention for speed, security, or some other performance reason.
Comments are for things that are __impossible__ to tell from the code.
db.insert(record); // save the record to the database
But when they write some crazy off-the-wall code (that's usually because they didn't understand the proper way to do something) I have to check the logs to see who wrote it and ask them why.
Just the other day I was debugging an application that had a 6 second sleep at the end of the main() function. I just figured it was some dumb thing left in for debugging and deleted it, because there's no good reason to do that. The next day, the dev who put it in messaged me and said he put it there because the application was exiting before it had logged it's completion to our logging system. So I explained that the proper way to do this is to flush the log, not just hang the application for 6 seconds so that the last messages just happen to go through.
If there was a comment explaining why there was a 6 second sleep, I could have just fixed it and educated the developer without causing any grief.
Look up Chesterton’s Fence. :)
(I made similar errors more than once.)
Throwaway commenting often makes people feel as if they’re adding value, whilst fulfilling their obligations.
Of course such comments have no value and worse, can distract from what ought to be commented.
Perhaps ChatGPT has found a use, if it is asked to add comments to code, although I somehow doubt it…
> One should take care not to overestimate the impact of language on defects. While the observed relationships are statistically significant, the effects are quite small. Analysis of deviance reveals that language accounts for less than 1% of the total explained deviance
Many functions in the standard library behave subtly differently from there documentation or have behaviour that is not documented but depended on by applications, and I’ve certainly seen lots of concurrency bugs in both code and tests because the GVL makes it hard to provoke the worst case behaviour.
The unit tests are really useful for Ruby language implementations because they help give us confidence we’re replicating all the required behaviour, but from that point of view I wish the underlying things were better specified so those tests weren’t quite so necessary.
Don’t get me wrong. I love Ruby as a language and loved working on TruffleRuby, but I don’t think the community should be too smug about code quality and testing.
You can tell everything with code, given enough time and resources. Nothing is "impossible". But there's a point where you hit diminishing returns. It's about efficiency.
Other devs, or your future self, will have to time trying to build the same "castle in your head" as you did. Can a comment shorten that time? If a one-line comment saves 15 minutes of investigation in aggregate, that's a no-brainer. You should add it. Conversely, a line that says "add 5 to x" is just wasting everyone's time.
As a general rule, once I have finally understood a particularly hairy piece of code, I don't want to do it again in 6 months. I have even done ASCII diagrams in the comments explaining how a particularly hairy piece of code worked, when I hated it enough.
It's something I wish was more common than it is. Sometimes you really want that ASCII pseudo graph explaining how minimizing this thing relates to that other thing that we actually care about.
Taken a step further, I really wish we had better systems for managing this type of information alongside a codebase. E.g. the whitepaper, or presentation, or figures, or whatever is often very necessary to understand the code, and ideally it would be under version control and live neatly alongside things. Nicely rendered docs definitely help with this (e.g. latex in comments), but I'm always surprised there aren't more people focusing on this aspect of information management.
I always assumed that behavior was dogmatic until, over many PRs, multiple members of the team commented that if I commented my code, it would be much easier to read. And comments of the above quality assuaged them.
That's just not true.
There are infinite many ways to write the exact same thing.
Your code can never say why it's like it is, why this approach was chosen and not another.
> […] the comments explaining how a particularly hairy piece of code worked […]
This kind of comments are the bad ones actually.
Your code should be clear enough that it's easy to see how it works and what is happening.
The rule is actually very simple, and I don't get it why so many people have issues with following it.
"Code says what and how, comments say why."
For my code? I agree
Code for others to participate in? The simplest possible way for the greatest number of developers to understand as quickly as possible. Not about my best practice or preference but for the greater good.
Coding standards for the elite devs are only so effective at growing that growing quick enough.
# this is going to loop 4x and call foo_bar on the 4th time because when you calculate this number it needs the 4th time to calculate the difference from the sales tax. weird, I know, but the business has special rules about how taxes work in California # Call foo_bar only on the 4th loop iteration to handle the weirdness of calculating taxes for California.
(I've just joined a company where everyone's constantly writing giant docs, and no one seems to grok the idea of a "living doc" that gets edited and refined. I think it's slowly making me allergic to verbosity.)I'm not sure I've seen all the "comment everything" advocates in this thread provide a single example of a good comment.
for i in 0..<4 {
if i == 3 {
foo()
}
else {
foo_bar()
}
}
}The python folks before me used this to avoid writing docstrings for modules/classes/methods, so code could only be understood by reading the entirety of it. Throw in some deep class hierarchies and it was very hard to onboard there.
If you're relying on comments to help with that, you'll have to share the same mindset as the person writing the comments, except there's probably multiple years of understanding gap between you and them.
In the simplest cases, sure you don’t need to write “getName returns a user’s first name and last name separated by a space character,” but I’m guessing the method requestPurchase will have a lot of nuance and I hope it’s documented (yes, even the “what happens”)
This would be actually a quite interesting comment as it indicates that the implementation of `getName` is buggy in regard to internalization.
Here's the classic post about this topic:
https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-...
I think there's nearly always value to be added:
* Explaining required fields, if null/blank/0 is allowed, where an ID comes from (db vs app-generated), if string values are formatted or require formatting (credit card, phone numbers), max length or other restrictions
* If a class/method is thread-safe or not (when not obvious and misuse is dangerous), error conditions, timeouts.
* Any external or indirect dependencies for use (config, packages, etc)
* Links to other docs/wikis or tickets is hugely useful.
When you're writing/working on the code you already know all this stuff, and it takes only a couple minutes to document. When someone else (or you, 6 months later) comes along to use or modify it, figuring everything out from scratch can take hours -- or worse, bug reports from QA or customers. Docs shave this down to seconds and directly avoid bugs.
The other huge benefit I often experience is through trying to write docs for something I realize there's a better, more obvious name that makes it easier to use and requires less explanation (less docs). This happens on easily 5-10% of the things I write docs for.
1. Rewrite your code to make the answer obvious.
2. If that's not possible use a comment.
/*
The phone number
*/
private static String phoneNumber;
That is considered 'the what', the documentation doesn't explain 'why' the phone number is a field on the class. This might be obvious because the class is called 'Address'... so people will argue that it is self documenting, and it is.The WTF code is 'the why'...
For instance, this [1] is a clean implementation of quicksort, which I offer as an example of any non-trivial algorithm. You can't really write it in a way that would make the idea clear to anybody who wasn't already familiar with the algorithm, because the idea itself is non-trivial. So the way intent is made clear and documented is by making sure the function is called QuickSort. And that is indeed 'self documenting', but really in a way that has nothing to do with the code itself.
[1] - https://www.w3resource.com/csharp-exercises/searching-and-so...
I worked with some Rails folks a while back who
were utterly convinced that comments were to be
avoided because it meant your code was not clear.
One of the few things that makes me want to reach a management position is my burning desire to alter this widespread, toxic, and absolutely bizarre belief.As an IC, even a senior IC, it's difficult to effect this change.
I'm honestly a bit torn by it. Yes, your code absolutely should be written in a way that keeps it tidy and easy to understand. But you've always got complex situations which arent always going to be easy or obvious for someone fresh to the codebase.
There should be a good middle ground. I dont need to see comments saying "this is a loop that gets all the users". If its got a variables called users, calling a methog called "getUsers()" then thats pretty damn obvious whats happening.
However if you then go on to do something weird like loop over each user and calculate a score based on the number of posts they've made then theres undoubtedly going to be some logic in there that even just a simple one sentence comment will help someone understand.
It's a fine line, and getting it right is a skill in itself.
I found that pretty much any methodology works fine in a team like that.
"Don’t comment the code" still sounds pretty crazy to me, but I can believe that it works for them.
While it's anecdotal, my understanding is that we were simply working on very, very different codebases. I was refactoring multi-million lines C++ codebases, implementing concurrent algorithms in which dependencies cannot be expressed through language constructs and I had to make non-trivial choices to prioritize performance, or safety, or security at the expense of readability.
On the other hand, these (few) developers were working on writing fresh code, with less footgunny languages, with simpler data and control dependencies and didn't need to make hard choices due to perf/safety/security.
Other times to comment include when there is some sort of dirty hack, TODO annotations, etc.
Obviously, unclear code without comments is better then unclear code with comments.
if (theWhy()){ theWhat() }
What this means is that if your Ruby code is clear it should read like natural language. Injecting subtitles into the middle of the expression
# I decided to phrase it this way because I was in a rush and it was the first thing that came out. With more time I could no doubt articulate this in a more communicative way, but for the sake of a random post on the internet I'm not terribly worried.
interrupts the flow when one is reading the code, which makes for a much less pleasant experience. Ruby may not be the only language that is like this, but it is relatively unique in this regard. Comments in other languages don't seem to cause the same interruption.
# That's all I've got. Time to clean up.
I'm not sure this means don't provide additional information to future readers that may be beneficial, but be discriminating in where you put it. Or do whatever you want. Who cares what someone else thinks?
The history of programming is full of that notion and it never really works out. See: COBOL, SQL, and so on.
I think we can all agree that code that is easy to read is better, but sometimes the 'why' needs spelling out.
Comment bit rot is inevitable, because comments don’t compile and can’t be tested. The only way to keep them in sync is by hand, which takes a lot of time and energy and is far from perfect. Of course,
> The first problem is that most developers are under great time pressure and don’t have the time to make the code so utterly clear that it requires no further comment.
So they don’t have time to write the code clearly, but they somehow magically have time to read and review all the comments and to keep them in sync with the code? And the reviewers too?
“If only developers worked harder…”. It’s nonsense.
Comments are great, they have an important place in software engineering, and I always regret when I forget to write some in a file or class. But they are not a silver bullet, and must be treated with suspicion, because there is no way to prove if they actually describe what’s going on. And that’s the same reason that they are hard to keep in sync.
If there have been major structural changes that make the comment useless- that’d be pretty easy to see, it’s very easy to delete comments
I'd argue you could do the same on methods and class you want more context on, removing the need for the majority of comments, and most companies will have the associated ticket numbers or design discussions attached to the MR/PR.
I think there will still be rare situations where comments are absolutely needed, but in these rare cases they should probably refer to an external resource (a bug report for a specific library, an incident that required a specific fix, etc.)
Exactly. I used to love writing comments, but they have become for me a last resort. I'd rather put the information I'm trying to convey almost anywhere else. Variable names, method names, improved interfaces, better object relationships, doc strings, test code, test names, commit comments, or my colleagues' heads.
Though I fully admit that automated tests cover nothing related to explanations / things that aren't inherently true or false.
Personally I've wanted a way to link code to comments, not just the reverse, so I can change code here and be notified that it affects comments over there, especially during review time (just show every related comment next to the change). It seems literally essential for reliable documentation, but I haven't yet seen it except maybe in WEB (the literate programming language) or similar.
but ... it's the explanations that are important.
I mean there are plenty of tools to check that a comment matches a function signature or otherwise describes the properties of a bit of code. But who needs that? At least in a strongly typed language, reproducing the signature or doing anything else that reflects existing code within a comment adds very little.
Anyway, I am not arguing against comments. I'm just arguing that they can't somehow magically reduce technical debt. Or that they have anything at all to do with technical debt. Or that the OP made any sense at all.
Often, yes! But you can also sometimes mechanically detect when what you're claiming might no longer be true, even if you can't assert the full content. E.g. "X does Y when you Z, so you should QWERTY periodically" -> check X,Y,Z in a slightly relevant way. Maybe have an example QWERTY call that does nothing but compile.
If a check like that fails, it means something has changed, which is an ideal time to check that documentation again. If it's not relevant, just fix the test. If it is, it shows why these systems are valuable.
(Yes, it's a change-detector test, which everyone hates for good reasons. They work great for things that are important but can't be sufficiently tested though, because the alternative is no automation at all)
Plus, the content that's truly hardest to check this way (high level conceptual docs, etc) is also generally the least likely to change in a meaningful way.
If your code is separated from comments explaining it so much thag this isn't visibly obvious on review, there’s probabky a bigger problem than “I don’t have a way to link commebts to distant code and vice versa.”
And fairly often that's significantly more useful information, or in a much more useful format, than the documentation of X on its own.
Not true in Rust
I don't want to write a comment, I'd rather write clean code that looks good, but when I run out of time to spend on a problem, and I don't think the code is clear enough, I think then it's acceptable to add a comment.
I just think too many devs have their egos wrapped up into their jobs, so hearing, "Commenting is failure!" evokes an emotional response. What these devs don't realize is you can make no mistakes and still "fail" to write clean code, and that's totally okay.
Uncle Bob is just saying that pulling out a comment before you've tried is premature. Try to avoid it first, if you have time to.
He has been trying to say profound things for a long time now. He was super active in the XP community in early 2k onwards and he was nearly always saying things that I felt were a bit "off". i.e. there was a gem of an idea, but the idea was turned into some principle or rule that lacked nuance and context. Reality is, there isn't any fundamental rules/principles... just ideas, some ideas seem more universal than others, but these ideas are just a bunch of strategies you can use when approaching software development and depending on context they may or may not be good strategies.
In terms of commenting, some of this weird "wisdom" around commenting was fundamentally rooted in the idea you can't fix bad code with comments. People noticed that a lot of times where there was comments in "poor" code it actually was a spot where you could do some kind of refactoring to make the code clearer. Eventually this morphed into "If you need to comment your code you have failed" type sayings. However, there was plenty of people advocating commenting to explain things the code can't tell you, but too many were swayed by "commenting is failure to write good code" that they threw out some of the reason why people like to put comments in. Many in their first 10 years of coding really want guidelines and rules and principles and argue strongly for things they have found effective compared to how they approached coding previously. But these things you learn are almost never universal, even if you can see/argue how you could apply it to all kinds of things, other approaches might actually work better, or might work better in different contexts.
One of such things is "screaming architecture". It is a good idea in theory, but only if you already know what the architecture should be. Most new projects don't know what they need up front, and discovery happens over time. Screaming architecture is bad for this process. It inhibits it, requiring a ton of refactoring because of early assumptions. One thing that is known up front is entry points. (CLI, requests, tests, bg jobs). They're a lot more likely to stay around forever. Custom architecture should emerge underneath them. I guess we can call it whispering architecture.
1. An odd business requirement (share the origin story)
2. It took research (summarize with links)
3. Multiple options were considered (justify decision)
4. Question in a code review (answer in a comment)
Code is writing, would you write a technical book without sections and chapters?
E.g. if the ide can't grok what a $var is you can do :
/** @var Some\Namespace\To\Class $var */
$var = ...
then when it reindexes things it has no problem tying everything together.For instance, it's great that code reviews have become standard practice at most organizations and for many projects, but the tooling for those reviews almost always rely on showing the few lines above and below a code diff. The reviewer has no convenient way of seeing how the changed code may conflict with any applicable comments unless the comments happen to be within those few nearby lines or the diff happens to include comment changes. Even then, the big picture is out of view and rot is still likely to seep in.
It would be nice if incoming developer-support AI could start tackling this, by surfacing impacted comments and even "linting" them for applicability and accuracy.
That only applies to comments that address what the code is doing or how it does what the comment says. It does absolutely nothing for the most critical type of comments: the ones that say why the developer decided to do it a particular way. Maybe they tried it three other ways and this was the most efficient way. Maybe they chose this way because it matches up with a business requirement that things be done in a particular order (regardless of efficiency). Maybe it must be done that way for consistency with another part of the system that is only obvious from the comment.
It will be a long, long time before AI will be able to reasonably vet such comments for accuracy. Until then, comment your darn code!
Documentation tooling should be able to make a good job of constructing a class/function DAG with scoped commentary. This is kind of a reversal of Literal documentation, but I suspect it may be more maintainable by teams.
Literal docs only seem to go in one direction, that is documentation->code, not the other way around. This I guess is more in-line with scientific hypotheses. Literal tests may be even more tricky as TDD doesn't gel well with Literal hypotheses.
I guess a Doc-driven dev process would be a novel approach here, and probably more usable than AI-supported systems. Copilot has been quite divisive on it's effectiveness.
DDD in that every eg. Class requires a comment and a test even if they are blank, to force at least a thought about them. Having a code manifest at the root of a repo can also be used to configure the envs the code runs in, and the integration tests that it needs to do both local and in-place.
Lastly, as mentioned elsewhere, logs are comments as well, and again would be well to be scoped in the language.
The other thing I wanted to mention: People don't do code review in their IDEs? Really?
Modern languages with type inference are not fun to analyze without an IDE… Also you can't navigate to related code without IDE features. Just looking at a diff can be very misleading!
I only recently started working in a big team again and when I'm doing Github code reviews I often find myself checking out the branch locally and reading the file in my IDE and then going back to the Github interface to write my review comments.
Not only is this often the only way to understand the context of a change but it also makes it much easier to spot refactoring opportunities. But it's cumbersome and slow.
6 months later I wont remember why the "easy" solution wasn't the path that was taken, or some complexity that needed special handling in a single case that was discovered through a few hours of debugging.
Sure you could write perfect code, but writing out your thought process helps tremendously with understanding a thought process and getting up to speed far faster.
My guiding principle is that I don't want someone to read my code years later, exclaim "Who the hell is this alyandon guy?!?!" and be motivated enough to create a time machine so they can go back in time and smash my keyboard to bits before I wrote said code.
Someone working on the code should know the language. If they stumble over something they don't know they should read the documentation of the language. Explaining the programming language you use in code comments is a terrible idea, imho. It's like writing comments of the form "adding the numbers" and than adding some numbers. Just useless noise.
The more important question would be, as always, why you used this feature? What would be e.g. the alternatives?
Just stating that you do something, just to do it than with code makes no sense. Nobody needs that redundancy.
It is difficult for me to understand why the debate surrounding code comments is so heated. I had some strong opinions about these things when I was very new to engineering but I rarely see anyone senior doubt the effectiveness of code comments. I get the idea of self-documenting code, but very few things are self-documenting to a new person on the team that never worked with your massive proprietary codebase. They need a lot more context.
I would like to see some examples of self-documenting codebases. Sadly, people like Uncle Bob who loudly hate code comments tend to have codebases that are not very self-documenting. Perhaps not writing any code comments is an interesting exercise, but I think it might work much better in small siloed projects than in companies where hundreds of people have to collaborate on the same code and not introduce defects. I wonder if this is where the disagreement about things like code comments comes from - different circumstances of the programmers.
It's an interesting exercise very similar to the infamous Perl one-liners from the 2000s.
>but I think it might work much better in small siloed projects
The problem here is that those "small, siloed" projects frequently get out of their silos and become bigger and more important than originally envisioned. Then all the new people looking at it have no idea what it's doing.
As a kid, I somehow got the impression that Microsoft had a coding standard for 1:1 comments to code. So I thought I'd give it a try. (I had a lot of free time.)
For the 1.x to 2.x version bump of my text editor, I meticulously went thru and commented everything. (I also switched to 1 statement per line guideline.)
The outcome was awesome. By requiring a comment, any comment, for every statement, it evolved into a form of story telling. I wasn't just explaining obvious stuff. It helped tremendously with future maintenance.
Alas, I've never repeated that experience. I'm not entirely sure why.
It's a bit like Knuth style literate programming or TDD. Some kind of Platonic ideal. An esthetic ideal to strive for, but not very practical.
Shouldn't that be expressed in a test? To me, "there's a special case that drives the code in a particular direction" is Exhibit A for "things that belong in tests".
Comments aren’t milk, they don’t just go off, developers let them go out of date.
As others have said, comments should be used to add why, to give context.
We preach endlessly the idea of orthogonality and abstraction, but then we smash together plain English and Python/C++/Erlang/whatever?
We agree code should be split into multiple files, why do we suddenly not agree that English should be split as well? Nobody would try to write a file with 30% JS, 50% C++, and 20% Python.
Discoverability and context would not be nearly as useful, to start. Why you need to ask the question, as if there is no suitable answer, is suspect of a thoughtless conclusion.
In the late 80s, there was an idea floated that every file could have a sister file with comments, such that they would not need to be parsed/discarded by a parser. This would aid in generating documentation, among other tooling. When I was starting out, I expected this to take hold, but it never did.
> There are so many better ways to document design and implementation decisions that don't involve embedding English into source code files
I don't think that's been demonstrated.
This sounds a lot like the director's commentary tracks on DVDs. No one ever watched those, and the sister-comment-file would flop the same way if anyone really tried it. A separate file is fine for documenting overall design, but for detailing sections of code, the commentary needs to be close to it, where people will see it.
Besides, if you foster a culture of writing "why" docs, the problem of where to place these docs is one you solved early on, so people will know where to go.
They need to if the the way it works is significant. If it is not significant then the value of a comment becomes somewhat dubious anyway as the code is expendable and doesn't really matter. It is not necessary to understand the program and if it is flawed you're going to rewrite it. Comments can add a lot of value, but there is a line where the value quickly diminishes.
"...team leads (and managers) allow comments to get out of sync with the code..."
reveal a fundamental misunderstanding of how software organizations generally work.
My personal solution has been to approach code documentation as programming in one’s native language, or as is often done, in English. Learning to comment is given the same importance as learning to code. Comment maintenance is given the same priority as code maintenance. Explaining the actual function and expectations by comment is the essential part of writing code that expresses the functionality.
Comments are given similar weight as code. Comment design is considered at an early stage. And comment maintenance is equally as important as code maintenance.
Why do we talk about coding rockstars but don’t we talk about commenting rockstars? This isn’t anti-agile or anti any methodology if it’s presented as an integral and essential part of the task.
Often, when mentoring such processes, the act of commenting liberates insights that may have only appeared during failed product testing.
Of course, learning to comment effectively is learning to communicate effectively. Metrics for effectiveness are often elusive and people are rarely paid for lines-of-comments, so this is always a hard sell, unless it’s understandable to be a core coding activity.
We see the same thing in related areas, like logging. Unless you need to solve a problem with the help of accurate logging data, you don’t see the need or utility of logging anything. As with comments and code, logging also needs consideration and maintenance.
Learn to code Learn to comment Learn to log
These mantra won’t come from above, so need to be learned and understood.
User manuals used to be pretty extensive, and filled with information not just on how the devices work, how they should be maintained, but also on what mindset these devices were built and the general context.
For instance I remember buying a vintage camera with the original manual, and it basically explained photography to beginners, including framing the subject, lighting, and shutter discipline.
Nowadays a smartphone comes with 2 pages of instructions on how to start the device.
Are we much worse because of that ? I'm not sure, something has been lost, but I also can't imagine a smartphone coming with 200 pages of explanations and addenda sent by mail on every OS revision.
A code that is regularly evolving in significant ways is to me way closer to a smartphone than a vintage camera.
Regular comments are subject to bit rot - they get less true with time. Unless actively maintained - eventually all comments lie.
Git commit messages maintain themselves. If a line of code was changed - the git blame annotation will change. So you know exactly what the context was and exactly which lines the comment relates to. It provides context (you can see in the commit what else changed with it), and if you include the JIRA task number and a short description - it provides the WHY.
IMHO the most important skill for writing understandable code is splitting the commits into sensible pieces and writing good commit messages.
I always check git blame before committing a new code, because I've had this exact experience several times:
- investigate a bug
- find the responsible line with obviously wrong code (often it's even nicely commented and the comments and the code are contradictory)
- fix the obviously wrong code
- commit
- 10 other bugs caused by your fix
- git blame
- turns out the "obviously wrong" line was there on purpose and your fix effectively removed a previous change
- which you would know if you checked the git blame for that line
- comments were lying because somebody did a refactor and didn't noticed 4 lines above there's a whole paragraph of what now became lies
This is Chesterton's Fence rule of programming. Before you change a line of code - be sure to understand why it was there. Git blame is the best tool for that.BTW there's a similar rule for comments - when you change a line of code in some function - you have to check all the callers of that function (and their callers, etc.) to see if there were any comments near the callers talking about the part that you changed. THAT is the thing that nobody does in practice, and THAT's the reason why comments eventually lie.
I can see you getProductCollection, I know what that does, but why do you do nothing with it? Oh it's because it needs to be loaded before presenting the cart, and there's a bug in the framework that fails to do so in this scenario.
Also business requirements can be reaaally asinine, a makeThisParticularButtonGreenSeeMeetingNotes20122023() would be pretty lame but that is often required information for a developer revisiting a feature and wondering if something was a bug or intended.
Stop being so dogmatic about comments and do what works for your team.
Such a flame war territory.
Sometimes things are just complicated and they require explaining the intent to help the reader understand the code. It also helps spot bugs or allows someone smarter than me to rewrite it in a better way (for different axes of better)
There are other situations where comments are useful that are covered elsewhere in the thread, too.
So, I've gotten some good ideas on how to improve my code comment etiquette!
First, the code needs to be fairly clear, but not "stupid" clear. I have had people tell me not to use idiomatic Swift, because "a JavaScript programmer can't understand it."
In some cases, this may be necessary, but not in mine.
The #1 consumer of my code, is Yours Truly. The wonkiness doesn't bother me, but sometimes, I may not be aware of why I did something (that may not be "idiomatic," at all).
That's why I may write a quick comment, like so:
showThrobber()
// The reason for this, is that we need to give the throbber time to show up.
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(20)) {
That explains the awkward use of an "asyncAfter()" method.It was the result of me, wasting a good half hour, trying to figure out why the screen didn't change. I saved future me, a half hour (and also a signpost for "improvements needed").
I write about my approach to documentation, here: https://littlegreenviper.com/miscellany/leaving-a-legacy/
When reading this I didn't understand the comment at first, before I realized that it's meant to say something about the following line.
It would be better therefore to write it like:
showThrobber()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(20)) {
// The reason for this, is that we need to give the throbber time to show up.Oh, an "argument" on the base of "We have always done it that way". So we don't have even an argument here.
And no, this nonsensical "convention" is not everywhere followed as people realized that code should be written in the most readable way possible.
I know a lot of human langues that are read form top to bottom. I don't know even one where you read bottom to top…
Jumping around mentality in code is a sure way to make the code hard to understand. Ever heard the reason behind why `goto` is considered bad?
Ever seen Python doc-strings?
Did you write your comment under my comment or did you write it above? Why is this so?
Also writing comments above leads very often to the kind of comments that describe what the following code does. Which is the most wrong type of comments, like it was said here not only once.
Comments below lead OTOH naturally to comments that describe why the code was written like it was written.
There may be exceptions for the rule and cases where it make sense to have something like a "heading" comment. But this cases are very rare.
If you actually think about it almost all (good!) comments make much more sense below the code that is commented as this is the natural way how to write. Just look how this site here is structured. And it's all about comments!
Bottom line: Use your own brain! Don't do things because someone told you "We have always done it that way"!
Thanks!
So maybe like so:
showThrobber()
// The reason for the asyncAfter(), is that we need to give the throbber time to show up.
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(20)) {
I tend to like to put comments to the right of the lines, but not if they are long ones.I don’t usually like to put stuff just under opening braces, because I feel that it can sometimes obscure the fact that a new context was opened.
Indentation is important. Back when I programmed C++, I used Whitesmiths indentation, but I changed to K&R, when I started writing Swift. With Whitesmiths, you can put a long comment, just above the context opening, and the comment can apply to just the context, and not the opening statement. This established a habit of having comments apply to the line below.
Here's an example of the same kind of thing, in another part of the same codebase:
if userFallbackRaw == (inError! as NSError).code { // Fallback means that we will use the password, so we nuke the stored password.
#if DEBUG
print("Biometric fallback.")
#endif
// Wow. This is one hell of a kludge, but it works.
// There's a "feature" in iOS, where the Touch/FaceID callback is triggered out of sync with the main queue (slightly before the next run cycle, I guess).
// If we immediately set the password field as first responder in this callback, then it gets selected, but the keyboard doesn't come up.
// This 'orrible, 'orrible hack tells iOS to select the field after the handler for this Touch/FaceID has had time to wrap up.
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(20)) {
self._bioHazard = true
self._selectedPassword = ""
self.emailAddressTextField?.text = self._selectedLogin
self.passwordTextField?.text = ""
self.isThrobberShown = false
self.passwordTextField?.becomeFirstResponder()
}Thanks!
int strlen( char * s );
the following comment pretty much describes what it does:
- if passed a null-terminated string, returns the number of characters in the string, excluding the terminator
- if passed a null pointer, or an incorrectly terminated string, behaviour is undefined
these are the kind of comments i like to see
Comments are vital, but I prefer everything be refactored to make the code the comments, which only happens if you get naming right, the language, libraries and the frameworks don't fight you. Which is a lot of ifs. Even then you need the comments to label parts of code that are exceptions to normal practice, or to fix particularly subtle bugs so that you prevent regressions from happening. (If you want tests to do that, it doesn't obviate the need for comments - you probably want the comments in the code and the test, because you don't want it to be standard practice when you are editing code to discover a new all the failing test cases when you make a change)
The data they cite on TODO items isn’t relevant as the experiment lacks any controls and is thus non-scientific.
The best we can do given the dearth of data is consult the market for answers. There are successful software companies/projects/individuals that subscribe to either philosophy (sometimes simultaneously) and the market doesn’t seem to care as it does about how good the product actually is. Stuff like this is bike shedding at best, at worst it’s a kind of virtue signaling to some group in an attempt to appear as a blessed expert.
DatabaseConnection connnection; // Connection to the database.
// Write a log line when the system is intialized logger.info("The system was initialized successfully.");
When I see such comments I am severely tempted to conclude that if one is going to have a policy on comments forbidding them would do less harm then mandating them everywhere.
1. if it is important to explain WHY something is done in a way it is done
2. if there is some related or directly connected code far away that the person might miss or cannot know about and how this code influences it. Writing self-explanatory code nowadays is a standard. An era of newbie spaghetti code is long gone so no need to explain the code itself.
The team ended up expanding the codebase quite a bit before that technology stack was retired a couple years later. Not sure if it would have survived without that refactoring.
So? Good comments are valuable, even if they aren't always kept absolutely consistent with the code. Comments shouldn't restate what the code says, they should either say things the code can't say (like why), or (sometimes) summarize what the code does at a different level detail to make it easier to understand.
The trick is to read code and comments together, and dig into source history when something seems off.
The code can have comments or not, it's more of a preference.
Of course, it is impossible to infer from the code why something was done so this will always be needed.
I suspect they drag down engineers, and cause them to refactor, or burn out.
But what if something like chatgpt could explain the code to you. If you could ask questions
"does anyone call this function?"
"who calls it, and what do they do with the results?"
"can you call it a million times, fuzz the inputs and see if it crashes?"
"can you replace the bubble sort with qsort?"
there are also places where you might want to explain the “why” even if the code is clear.
relying on comments to understand the “how” has been a smell in every codebase i’ve seen.
* Comments are excuses
* They're used to validate the existence of crappy code
* They do nothing for you in production
Instead:
* we commit to writing log messages... which are sort of like comments, but they work in production
So-called "level of intent" comments as well as comments highlighting tradeoffs, gotchas, flaws, limits, exceptions, assumptions, and so on, are incredibly valuable if you preserve them alongside the code. Comments explaining why this function exists and what it's for can help you quickly come up to speed on a new code base - this is especially helpful when it comes to handing off code to a new owner or expanding the team of owners. The following code may or may not be well written (who can say??) but it's not exactly inviting new contributors: https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/moti...
Around the time of writing the code, comment-free code looks clear to the author because they have the benefit of all of the thinking that went into writing the code.
I'd argue that in production is when comments are often most valuable. The middle of a crisis is a terrible time to wonder what assumptions were made when writing code a specific way, or if a certain line of code that seems to be doing something weird really is weird or if it was based on something you're not considering. It's also the time when you want to maximize the number of people that can jump in and help.
Everybody has their own coding standards and there is certainly some subjectivity to those standards. Here's mine for people who work for me: if you don't document your code, you have no business touching anything that goes anywhere near production, you can't do anything that is critical path, and you should make a sincere effort to change or start looking for another job. :)
But I need to point out: The code sample is just hilarious!
Typical C code… Not even correctly indented. ;-)
I will never get those people creating all this write only code.
The C hackers seem to even think chars in symbols are scarce, so they still name them like `c`, `d`, `s`, `pp`, `me`, `mv`, `qpel`, `fx`, `bx`, etc.
Paired with zero abstraction (because C is not much more than a macro assembler) this creates the most horrible code I can imagine.
//-----------------
// <date> This is to work around a bug in the third party
// function foo() (filed bug report #foo234). This code does ...
//
// <date six months later> foo() still not fixed.
//
// <date one year later> foo() still broken. Bug report returned as
// WONT-FIX. Sigh.
//-----------------What the hell is that supposed to even mean? Then writing log messages are excuses too.
Version control, code style conventions, and testing have nothing to do with explaining how something works or writing about potential pitfalls of this function if some other core logic were to change etc.
Absolutely baffling you guys are arguing for never writing comments.
Comments are for things that are __impossible__ to tell from the code and the code alone.
Comments are subjective, code isn't.
90% of the companies I've worked at have had commits linked to actual tickets in a ticketing system. if i really need to understand what was going on, holistically, i could just git blame and go there. i look at tests, I look at the discussion around the code between the person who reviewed the PR and the person who raised the PR. Too often people use comment incorrectly or noisily.
No one is saying you shouldn't write comments. People are saying there are way better practices out there and you should really ask your self, why you are writing a comment to begin with and is there a better way to capture what it is your are trying to do so product managers, developers, engineering managers, QA people understand what the intent of that commit was.