193 comments

[ 3.1 ms ] story [ 241 ms ] thread
A comment at the end of a long block can be helpful. If you have to scroll up to figure out what block just finished
If your code block does not fit in the window, it's too long. You don't fix that with a comment. You should break it apart into smaller units.
Or you need a bigger monitor ;-)
One that's missing: comments should explain why a piece of code exists or is written in a certain way (and implicitly, when it can be changed or removed). This overlaps with "explain unidiomatic code in comments", but there can be idiomatic code whose purpose isn't obvious.
I once worked in a codebase full of such comments, they were all like

// Adding this because XYZ said so

Sounds like a plain-language version of "git blame"!
I've also seen it where every comment was just who made the code change and the date. "John K. 10/13/1994"
+1 for this. It also links to my #1 rule for comments: why not. It applies when:

1. There's a chunk of code that, on first reading, could be clearer/simpler/more idiomatic.

2. There's a good reason not to use the obvious approach, and do something else instead (maybe performance).

Then comment to explain why the obvious path wasn't taken. No matter how well written, code alone can never explain "why not". I've found this invaluable, even looking back at my own code.

“Why not” is one of the top reasons to write a comment. It should be discussed more. Many times I've encountered a piece of code which could have been much simpler or idiomatic. Upon rewriting, I discovered that it didn't work for some obscure reason. If there's no comment explaining “why not”, many others (including future me) could lose time trying to do the same.
I think "why not" is one of those things which definitely does not belong in comments, if you regularly write up such justification, your code becomes mostly comments. Even more so than "positive" comments, "negative" comments belong in the commit message.

Possibly unless your entire codebase is literate, and code is secondary to comments.

honestly it needs both, but if you only put it in 1 place put it in code.

During the development you are mostly likely looking at commits, or PRs, so that makes sense.

But if its long living piece of code, people will get you your code via following function/method chains or just browsing the source not commits. While you can use git blame, and then figure out the commit, and then read last few commit messages, putting comment on code is easier on everybody.

Man, I've been bit a few times with this. I'll read code and think, "Why the hell did they do that?" Later, when I'm almost done re-writing it, I see the edge case they were working around.

At the very least, comment these situations.

When I started many aeons ago, when I did not know what I am doing, so I tempted to documented the language itself:

inc al ; add one to al register

In my long experience of writing and reading code I think that comments have mostly been absent.

I think that lists of best practice for comments are mostly irrelevant because most developers simply don't write them.

So, unlike Peter Vogel, I would rather have some bad comments than no comments if that is the price I have to pay for worthwhile comments.

What is it about software development that makes people think that yet another list of things to do will make things better?

If I were to create a rule regarding comments it would be this: code review should include reviewing the comments.

> So, unlike Peter Vogel, I would rather have some bad comments than no comments if that is the price I have to pay for worthwhile comments.

IME people who write bad comments never write worthwhile ones, so that doesn't seem like a tradeoff, unless you mean a binary choice between allowing or forbidding comments.

> If I were to create a rule regarding comments it would be this: code review should include reviewing the comments.

Isn't that usually the case? And it's not that hard. The issue I usually hit is that code review should include reviewing the commit messages, and while others may (I really have no idea) github has even less support for reviewing commit messages than they do PR contents.

> IME people who write bad comments never write worthwhile ones

It takes a lot of expertise to extract which information (mostly the "why", sometimes a reference you used while coding) is actually useful as a comment.

I also think you need to come across comments that helped _you_ understand other code to learn what good comments are.

Sure, so people with more experience should be demonstrating good practice here, as in other areas, by writing good comments for the newer people to see and gain experience with.
Notice that this only makes sense if a "bad" comment is somehow still "worthwhile." And we'll incur the cost of writing and maintaining (and, apparently doing code reviews on) bad comments to get there. And that ignores the cost of programmers reading and attempting to process bad comments.

Personally,I would rather have well written code than bad comments...and I think programmers can actually create well written code. I question whether we should reasonably expect our programmers, after creating well written code, to suddenly acquire the skillset for writing "worthwhile" comments.

Peter Vogel

Comments are an anti-pattern. The more comments you write, the less code gets deployed to production. Only code that's deployed to production counts.
Comments explain why the code exists. When you write a comment, you see sometimes that the code is not necessary.

Not necessary and removed code is the best code.

The best code is the one in production. All other code is useless.
The best code is the code that solves the user's problems
The best code is in production independent of anything else.
hahaha amazingly I actually heard this in real life a couple of days ago... something along: "you write more comments than code! that's not productive!"
And it's 100% true. The job is to get it out to production not to write essays in comments. Always be deploying.
I always thought my job was thinking, not writing? It should be about finding a good solution to the problem, not cranking out code like a madman.
No, you have to crank the code out to production as fast as possible. Ship it all the time, every day, tens of times a day. It's a war zone, not academia where you can think all day.
Nah, sorry, I don't buy that. I'm not in a "war zone", I'm building a product for humans, and would like to earn a little so I can enjoy life. Going to war doesn't spark joy for me, but if that's your kink, I'm not stopping you.
Running a business is always a war. Either you deploy and win the war, or you are still thinking about the code you will be deploying some day and lose the war to someone who deployed.
If someone is just one deployment behind you, it may be time to work smarter, not harder.
Just one deployment? To win the war you need to be hundred deployments ahead.
You can still ship early and often while adding a comment here and there so tomorrow you'll understand what you wrote and won't have to figure it out all over again
Agree here but:

   // not a longer comment than this
I may have been hanging around on Hacker News too much, but I can't decide whether your comments are sincere or an attempt at parody (I hope it's the latter, or I pity Mr Krumins' employees).
They are doing great. They love deploying! Deploy or die is the mantra we have.
If you’re not English speaker, do you always write comments in English, or in your native language? I personally see the latter as bad practice - in 21st century it’s almost impossible to expect that your code won’t ever be read by a foreigner. But I wonder how do you feel about it?
I am not an English speaker, but everything that ever went into my code was always in English, including names of variables, types, etc. Programming languages are in English and there is something that irks me in having another language mixed in.
Agreed. But I also discovered that in some domains local jargon doesn't correspond well to its English translation, or is not available at all, which is likely the case in law and accounting. In such cases, I go with the local language.
Then it’s important to add a good English comment explaining why the local jargon is used, right? :-)
Exactly. I spoke about comments only. I can turn blind eye on occasional non-English comment or short note here and there. But naming variables and functions in local language is an inexcusable sin. I am from small country of Czechia with 10 mil people. Naming function in Czech is utterly stupid. Even if you’re sole developer, there’s a good chance you’ll want to paste a snippet to stackoverflow, sooner or later have a collaborator from nearby Ukraine or Pakistan (very common), or god forbid! - your product will be so successful someone will want to buy it. Good luck if the code base is littered with language nobody speaks :-)
The problem with Czech is our extended alphabet and, more importantly, conjugated forms of verbs and nouns. You can't make the code sound good without proper conjugation, but of course no mainstream programing language supports it.
At least here work language is English comments, jira tickets, code and so on. even when orginal team is fully native Finnish speakers next guy might not.
Code (variables, ...) are always in english, they are most of the time shorter than german words.

Comments are in my native language, if i am absolute sure, that this code will not be used by any other people.

You can never be sure :-) Don’t you paste snippets to SO, GitHub issues or forums, when seeking help?
< do you always write comments in English, or in your native language?

Same language as the codebase, so usually english.

It can make sense for the codebase to use local naming conventions e.g. for legal, accounting, or administrative concerns: the ideas and concepts don't necessarily translate easily (or at all) and all the reference documents are in the local language in which case the codebase will probably be better off using the local language, and both comments and commit messages should match.

All these discussion about comments miss the most important point of why we need comments: To aid us in understanding the code.

My only rules to write comments are:

- Add “why” comments when you write the code

- Add all the other comments when you read the code, and don't understand

I wish I could make this the accepted answer
(comment deleted)
"Rule 6: Provide links to the original source of copied code."

StackOverflow looking to get more backlinks from GitHub/GitLab :)

That was my first cynical thought. It is a good rule regardless.
What search engine prioritizes links in comments or code blocks as any sort of signal?

I have no particular attachment to SO, especially after the way they handled their public drama recently.

That said I put a link to SO any time I have to look something up there and it’s not immediately obvious from the naming/docs why it does what it does. I also try to sum it up in a sentence or two if I can and if it doesn’t distract from understanding the larger goal of that section of code.

Also, find the real source of what you're copying. The formula they cite for brightness is a rounded version of BT601 luminance. Citing the standard in the comment is way better than just linking a random SO answer.

Links are mutable, links die, SO answers can be edited. Include any information needed to understand the code into the comment and proper copyright acknowledgements if you copied it (assuming the license allows it).

Yes! The comment may not even have been necessary, if you extract into a function calculateBT601Luminance(red, blue, green).

Then you can link the standard, or at least the Wikipedia page, and I would lean towards this if I don't expect readers to know a bit about the domain. But if you don't, someone can still find an authoritative source with a single search.

Sure, but also it may be worth noting that the content license on Stack Overflow posts requires this. And it's the poster's content, not Stack Overflow's, so there's an element of respecting a fellow coder who helped you. In fact, most open source licenses require attribution at a minimum.
When you solve something in a weird way, leave a link to SO in a comment.

Write TODO and NOTE and use a tool to find all your special comments that show unfinished features and investigations. Scan through regularly to make sure the comments still make sense.

Comments not containing special strings should just be "why" explanations, eg "we sort the bids in the reverse order to the asks because the best bid that the highest price". So generally something where the code has special cases that are explained by the domain.

Within the domain of electronic trading it should be obvious that prices are ordered from best to worst, and that it means increasing order for asks and decreasing order for bids.

You shouldn't comment on things that are obvious within your domain.

Now you may put a comment if instead you sort things in the reverse order than usual, for example so that you can implement adding/removing a price level at the top more efficiently with std::vector (which is only efficient fot additions/removals at the back).

> Now you may put a comment if instead you sort things in the reverse order than usual, for example so that you can implement adding/removing a price level at the top more efficiently with std::vector (which is only efficient fot additions/removals at the back).

Though in that case you should probably have a comment explaining why you didn't use an std::deque.

I'm not sure what such a comment would say?

The advantages of vector over deque should be well known to any C++ programmer.

It's more that there's an asymmetry and sometimes that raises a question. You're right I could have picked a better example.
Comments are often a sign of code smell. If you have to explain the code, is it too long or too complex? Short functions, better naming, and so on. Other than that those rules seem reasonable. Specify intent over implmentation. The code implements, the comments explain the reasons, if any.
To you as the author it might be crystal clear, but the next person who has to modify might not have the full context. A lot of good comments in this thread mention that you should write comment about intention (“why”), not implementation details (“how”), although also the latter might make a significant difference to the next person. And even if your original code might have been clear to another person, it might have been modified in the meantime.
> A lot of good comments in this thread mention that you should write comment about intention (“why”), not implementation details (“how”)

Erm, that's what I said above. I don't believe that's controversial.

And neither is the fact that if there's a 30 line comment above a 100 line function, perhaps the function should be reduced in size because it's clearly complex. In fact, IDEs such as Intellij will flag it for complexity

Commenting for the sake of it, especially due to poorly named functions and variables is a code smell. Code is for the reader. The compiler doesn't care if your variables are two characters or twenty.

Breaking up a function doesn't always make it easier to follow. Instead it sends you bouncing around, trying to keep track of all the values passed back and forth. Some things you need to do are just complex because there's lot of complex rules and mathematics.
Kernighan's law is fun.

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.

If effort is linear then, by definition, you should never put more than 50% brainpower in to your code.

I'm not sure I want to increase the effort I put in though.

Only if complicated is considered clever. Clever might actually make things simpler.
Only in the mind of the person writing it.
(comment deleted)
I believe "cleverness" refers to ingenuity; it's outside-the-box, and trades simplicity in one plane for sophistication in another.

However most "clever code" we come across is lopsided in this tradeoff, and might even require cleverness to understand, which it turns out is not very clever at all.

I write my comments in commit messages because those are valid forever. A lot of times somebody will write a code comment, the code will be changed, but the comment not. This is a huge waste of time on so many fronts: writing the comment in the first place, and then confusing the subsequent developers with the wrong information. If you truly want to understand something, you can always check the change log, and find out why things are how they are.

Exceptions are e.g. if it's something exceptionally tricky or a hack of some kind that is kind of important. It doesn't happen all that much because the stuff I work on is simple. If I was going to do a lot of "commenting" I would prefer to write and update good documentation that gives an overview of how different things work together. The nitty gritty changes too often and is not that important in the grand scheme of things.

(comment deleted)
> I write my comments in commit messages because those are valid forever.

Don’t they disappear when someone squash merges branch where a file is both renamed and changed (a lot)? Or, at least, when somebody decides to move to code to another repo, and doesn’t bother bringing the git history along.

squash merge is evil
I feel differently, why don’t you like it?
The above-posted scenario is a great reason to hate it. It's destroying developers' documented rationale for each change.
it destroys information for no good reason
The author should squash useless commits. A readable series of commits is put to review. At merging to a commonly used branch no more squashing.
Why?

Why doesn't the author make commits that are not useless?

Why squash everything into a single commit? Why not 2 commits, 3, 5?

Yep. I make a commit on every little change and every team I've been on makes me squash them on merge.

Comments in Git commits are bad. Just comment the code and make sure the comments are updated while you're in the code. You can also look at them in a code review. The argument that they get outdated is easily remedied, but people just want to keep claiming they write 'self documented code.'

I dunno if he really meant that, or just said he is explaining the added functionality in detail. I do explain in the commit message the feature I have just added.
> make sure the comments are updated while you're in the code. You can also look at them in a code review.

People will invariably forget to update comments and unless the comments show up in context lines of the diff associated with a change, it's likely that reviewers will overlook the need to change them.

You comment is a standard explanation for not having comments. Always makes me wonder why stale comments aren't flagged during code review? Seriously failure to update comments should eventually lead to constructive dismissal.
I don't think "constructive dismissal" is the phrase is you want there. (That's normally associated with employer wrongdoing or, at a minimum, mischaracterizing the terms of an employee's departure..)
Everyone has to be onboard for that to work. Lots of people just never look at comments because they don't trust them.
I don’t understand. Can you not squash your commits and rewrite the message before you merge? Wouldn’t that preserve the message? (Trying to think of a scenario where it wouldn’t…)
Git commit messages and code comments serve very different purposes, I don't see any reason to try to use one for the other or opposite.

To me both are important but for different reasons. I don't want to search the blame history of a line of code if a simple comment had been enough, neither would I want to primarily use code comments when bisecting.

> … when someone squash merges…

It depends on who the “someone” is I suppose.

I typically squash my own commits, and as part of that I aggregate all of the commit messages into a single message with all of the relevant details (and leave out the “fixed typo” type stuff that’s not relevant.)

From the complaints that people are raising here there must be dev shops where someone else decides to squash a bunch of commits and throw away the messages.

That’s horrible because the git commit messages are easily lost, disconnected or hard to find in any reasonably active codebase. For example as soon as you do a change and move a file it almost always disconnects from the previous change history.

Whats even more difficult is searching through a code base when the documentation isn’t in or near the code. I don’t know any IDE or editor that makes it easy to search though git commit message and source code at the same time.

On top of that, do you review git commit message in code review? Do you aks people to improve descriptions, typos and language in commit messages?

  git log --follow -p file
edit: here's another

  git log -p -L:show_commit:builtin/rev-list.c
> I don’t know any IDE or editor that makes it easy to search though git commit message and source code at the same time.

Any editor from Jetbrains with the GitToolbox plugin does that.

Can second that. Having the commit message as a virtual comment on the end of the current line is immensely helpful in tracking changes. It’s like git blame on steroids.
I also like seeing the commit messages in this way! In the case of VSCode this comes with the Git Lens extension.
I don't understand how they are hard to find. It's trivial to find where the file was moved from.

What I truly care about is why something is the way it is, what is the rationale behind it, how it works with other parts of the codebase, what problems it solves, what is tricky about it, what to pay attention to and so on. I don't care at all about the code that was written and an explanation to it because this I can read myself in the code. The best place I've found for this is a code commit because it can tie different parts of the codebase together and add a lot of context to a change. I commit heavily and don't squash. A long comment in a commit that contains all file changes related to a certain feature, bug or whatever adds a lot more information than a comment in one file. When other people do it, it helps me a lot more than chasing their (outdated) code comments throughout the codebase.

But if that doesn't work for you, then don't do it. Just don't be dogmatic and dismissive. I accept there might be situations and codebases where this doesn't work.

Lot's of IDEs and external tools do very basic git integration ¯\_(ツ)_/¯

I think JetBrains is probably the best of the IDEs

I'm lost. Are you talking about meta-level comments, like "here's why this change is being made", that aren't directly tied to any particular line of code? If so, certainly putting that stuff in commits makes sense.

But for regular "explanatory note about this variable/function/etc" comments, how does one work if those things are in commit logs? If you're reading code and something is unclear, do you look back through the commit messages of every commit that's ever touched that line, just in case one of them has something relevant?

IDEs can show commit history. But you're right that it can get messy tracing back to the original commit when a file has been changed many times.

But for the most part I feel like comments should be automated tests. If a line is there for an edge case it should have a matching test for that edge case.

The only exceptions I see are for performance optimizations or some other situation where you can't easily test.

Tests are not a replacement for comments or documentation. Tests check that A() returns x but don't explain what is A, x and why it should return it.
That goes in the test name. You'll have something like

Feature A

"It should return X in [some edge case]"

That's where any link to a use case should be.

> IDEs can show commit history.

How you check the commit history is beside the point - the question is, do you read the entire commit log history for a chunk of code before editing it?

If not, any comments there might as well not exist - functionally speaking you're maintaining an uncommented codebase.

Your comments applies very little to commit messages, and much more so to comments.

> That’s horrible because the git commit messages are easily lost, disconnected or hard to find in any reasonably active codebase. For example as soon as you do a change and move a file it almost always disconnects from the previous change history.

Learn your tools or get better ones, `git log --follow` has no issues with renames, and when files get munged in ways it can't handle (e.g. content is split out or merged) it's easy enough to stitch back, and good annotate UIs (Jetbrain's is stellar and one of the few things I don't use magit for) make flitting through a snippet's history trivial.

Meanwhile finding removed comments is nearly impossible (VCS are nowhere near as good for finding when was removed than when it was added), and comments can easily drift apart from their point of origin as developers aren't too careful about maintaining them when adding unrelated comments.

> On top of that, do you review git commit message in code review? Do you aks people to improve descriptions, typos and language in commit messages?

Bet your ass I do.

> On top of that, do you review git commit message in code review? Do you aks people to improve descriptions, typos and language in commit messages?

Absolutely I do. The commit message is part of the commit just like the code; why would it be excluded from review? The number of times that a good commit message has helped me when dealing with a bug, and that a poor one has stymied me, have firmly convinced me that they are just as important as any other project documentation. They should be clear and informative, and I ask for those aspects to be improved when needed.

> I write my comments in commit messages because those are valid forever.

Only until someone moves a file to a new directory. Now this file shows up as a new file with no history.

Also, you hope to never change your version control system because that change will erase the history.

Relying on commit messages is sometimes just not good enough.

No it doesn't. At least git tracks and follow renames
> Only until someone moves a file to a new directory. Now this file shows up as a new file with no history.

Git will usually be able to link the two back, unless the move was combined with a lot of changes, as it does not record moves but infers them.

Even if it can't link them, the "creation" commit will visibly remove the old file, at which point you can... log / blame on the previous location and keep going.

> Also, you hope to never change your version control system because that change will erase the history.

Of course not, there are conversion tools between basically all VCS, and anyone tasked with such a migration who is not a complete goober will use them in order to maintain the historical record.

At $dayjob we've got history spanning over 3 different VCS and more than 15 years, and that's including weird stuff like splitting and merging repositories.

That's why renames should be a discreet commit and why squashing is bad
Making a rename in a discrete commit is less discreet (and therefore preferred).
Same thing here. At work I can see the history going back to 1995. And that's after migrating from something to Mercurial, and from Mercurial to git. Maybe that's not the case in all companies, but in the one I work at, the commit history is the longest-lasting information trail.
That's a great idea. I've been doing this just to rationalize my laziness, but now it makes sense. However, I'm not sure those are valid forever as you can simply delete the .git folder, can't you?
> However, I'm not sure those are valid forever as you can simply delete the .git folder, can't you?

You can also format your hard-drive, yes.

and burn down the stupid remotes
> I write my comments in commit messages because those are valid forever.

I try to write good comments and commit messages. Comments are typically along the lines of explaining what was done and how for a particular block of code or method. Header comments include a list of parameters, return values, side effects, class variables, etc. Commit messages explain what was done or changed and why.

> Header comments include a list of parameters, return values, side effects, class variables, etc.

These are only useful for public stuff and in special circumstances in other cases. Sadly a lot of companies make stylecheck require them on every little private method which makes each file 50% longer for no reason and drown the really useful comments in noise.

> Comments are typically along the lines of explaining what was done and how for a particular block of code or method.

The problem with that is that the block of code that you explain will often call other code, and then that other code will change for other reasons (preserving the correctness but not the initial design that was in the comment) and then that explanation higher in the callstack won't be true anymore. It's nice to pretend we always check everything that calls our code all the way up when we change stuff, but in reality if tests pass and the code works - we often don't check for comments up the callstack. So the comments will drift away from the truth with time.

Comments in commit messages are much more likely to be true than static comments in code (for example if you refactored some method signature as part of the change - every call site will have the updated commit message automatically). If you comment in the code manually - you will probably not notice that you have to change a comment block 5 lines above the changed function call - it won't even show in the diff - so the comment block won't be true anymore).

This sounds like a recipe for write-only comments.

The point of a good comment is to guide later development - to say "here's something you should know before editing this code". If you put information like that in commit logs, then that implies that anybody who updates any part of that codebase must first read every log for every commit near what they're editing. If they don't (and they presumably won't), they'll never see that "here's why we're not doing X" comment before they change the code to do X.

Meanwhile, it's true that comments can drift away from truth over time, but putting them in commit logs doesn't change that in any way. An inline comment that's stale can be updated (and doing so is part of the job!). But a commit log comment that's no longer accurate will stay there forever, waiting to mislead anyone who finds it. The promise that it was accurate when originally written is of no practical use later on.

So if you added several classes and functions, you describe them all in a single commit message? Probably you don't document them at all.
Commit messages don't necessarily last as long as the code that they comment though.

Changing revision control system or copying code from one package to another can lose them.

The only durable documentation I've seen is in the source code

One instance where I've found writing lots and lots of comments helpful is for functions with code that I'm writing for the first time. It's like rubber-duck troubleshooting - making myself explain what I'm doing in plain language actually helps me reason about it. I tend to leave those comments in because then the next person who works on it understands why I did something in a particular way. This perhaps results in superfluous comments, but you're never going to get it exactly right, and I think erring on the side of too many comments is probably better than too few.
Are you familiar with Literate Programming? https://en.wikipedia.org/wiki/Literate_programming
Thanks for the pointer - I had read about it, but hadn't put two and two together. The kinds of things I work on (cacheable wesbites) don't need to be highly tuned for back-end performance, so I guess it's easier for me to do that.
Lit style probably doesn't have much impact on performances, it's handled by the parser and mostly by ignoring the comments.

It can impact the memory of runtime-oriented languages, especially if they keep the text around (e.g. for reflection or whatever) but that's about it.

The problem with lots of comments is not primarily clutter, but as quoted from the article

Writing and then maintaining comments is an expense. Your compiler doesn’t check your comments so there is no way to determine that comments are correct. You are, on the other hand, guaranteed that the computer is doing exactly what your code is telling it to.

Unless your team has the discipline to maintain them, don't litter the code with comments. Put it in the commit message. Obsolete and incorrect comments are just confusing.

What I sometimes do is write comments before I implement something. This provides a clear idea of what I need to do and where. Then when it's done I cut it into commit message or note

I do this in a markdown file, and then check that file into a /docs folder. That way, it doesn’t muddy the code, and even though it becomes inaccurate over time, it’s still handy for a “what was I thinking?” check.
I believe random comments often become extra clutter and diversions from actual code. Code should have short, succinct names that explain in context.

What we should do is document the code, short and consise description of classes, methods and functions. This will then act as a reference, when names inevitably fall short.

From this discipline, comments above code-blocks should explain what's missing in code to a future reader - probably yourself even. But a basic explanation of "What the heck is this? What is it for?" might be in order, if not already given.

How to implement this depends on needs and tooling.

The bigger picture belong in design documents, with references to components.

John Ousterhout spent a (short) chapter on writing comments in “a philosophy of software design”. The whole book is in my opinion a must read and gives advice rather than claiming it has all the answers. Back to original topic: including how and when to write comments
If you are parsing/manipulating a particularly hairy data structure, try to simplify it. If you cannot, put a comment with a simplified example of the input/output data structure(s) so that the the next developer (which may be you few months down the line) has something visual to match the code against instead of having to imagine everything.
Yes! I love the data input/output example in a comment. So few developers do this
I think comments should be used much less than we have propagated for years. First, idiomatic code often doesn't need any comments at all. Second, every project requires some level of documentation, but the documentation should be a high-level abstraction of the code.

So the documentation is the easy way for humans to understand what is going on and when I want to know the details, I can jump into the code. And just if the code itself is so complicated or its implications are not easy to understand (which should rarely be the case), then comments should be used.

However, the problem with this mantra is, that the original authors often don't know/want to know when their code is not simple enough ;-)

It goes both ways. As a C programmer I'm inclined to make certain streamlines or optimizations that, when I show them to my peers, exemplify that I am NOT writing idiomatic code. But to me and my niche online C community the approaches are completely obvious and even viewed as elegant.

Do I add comments or not? Should the person reading my code "just learn" how it works? Or should I "just realize" that I am using advanced patterns that few people know?

Your exhaustive test suite is the technical documentation.
> Rule 6: Provide links to the original source of copied code

I learned this rule viscerally early in my career. Back in the golden age of Experimental Flash Art there was an enigmatic site called "flight404", and one day the site's author released source files for some of his more popular projects. All the Flash devs in my office started poring through them, and soon after my boss called me over to show me my own name in one of the comments!

Apparently the author (Robert Hodgin - whom I very much looked up to) had asked for help anonymously in a forum, and I had helped him out so he credited me in a comment (just for his own reference - in those days there was no Flash open source community and designers rarely distributed their source). That experience made me pretty obsessive about crediting outside influences in my source code whenever I get the chance.

More often than not, I see code without any comments. There's this idea of writing self documenting code that really changed the commenting world.

And that whole thing was evangelized by Uncle Bob and the Agile wrecking crew. Before long it was bad to use comments, switch statements, or new up an object. This, in turn, led to the TDD movement, Agile only movement, enterprise patterns for all projects movement, and I'm sure there are others I'm forgetting.

Please comment your code. Tell me what you're trying to accomplish with this block of code. The function name doesn't always suffice. And I don't want to stare at it for 15 minutes, or re-format your 160 column LINQ statement, or Google your regex so I can read what it does on StackOverflow.

Even commenting pseudo code would be fine.

Yeah it's often really worth giving some examples of what you're trying to match (and not match) next to regex code.
That's one of the real world mysteries for me.

* If you ever had to maintain a code base you didn't design (who haven't ???) how can you not want to have as much paper trail as possible? Especially when the original authors move on.

* I don't remember discussing documentation (or even testing) styles/preferences during interviews. I don't remember managers making it a priority or educating the unwilling, even in large companies. So it's clearly not important from the business perspective. The closest I can remember was a mad rush to create runbooks after a particular nasty prod incident.

We live in a world of microservices. So you routinely work with multiple repositories. In larger companies developers routinely move to different teams in a couple of years. There's always another AWS service or non-relational data storage. It's interesting to notice that in other domains dealing with this kind of complexity and constant change it's expected to have written notes all the time. Think of medical doctors or aircraft maintenance crews.

When I was younger I kind of trusted that "self documenting code" promotion. As much as the Refactoring book was right this idea proved to be just wrong. Think about "business logic". Including the classical "converting XML/JSON to other protobuf/JSON". There's no grand theory here, just multiple confusing details influenced by previous versions, legacy ontologies, dependencies on other teams. Naming conventions won't help much, not to mention "the two most difficult problems in CS".

I think there's some correlation between poor documentation and missing tests. And the lame excuse is always the same - not having enough time. Even for obvious error-prone things such as calendar calculations or parsing deeply nested data received from the outside world. Or how to build and run a service.

Another correlation is between clear/structured thinking and how easy it is to explain the results. A reasonable functional decomposition and popular idioms/patterns/libraries documented elsewhere enable terse descriptions.

I see documentation as fungible. There are multiple somewhat interchangeable places information can be stored in. JIRA descriptions, commit messages, "javadocs", MD files (previously known as GOOG docs, wikis, Word documents). From what I've seen the people who have enough discipline to use one usually have others in place too.

Software development is very much a learning process. So other people will have to repeat it unless you summarize your findings for them. For some low-level details you could be one of them after not working on a particular component for long enough.

  // NOTE: At least in Firefox 2, if the user drags outside of the browser window,
  // mouse-move (and even mouse-down) events will not be received until
  // the user drags back inside the window. A workaround for this issue
  // exists in the implementation for onMouseLeave().
In Firefox 2, mouse-move events cease after dragging outside window.

  // TODO(hal): We are making the decimal separator be a period, 
  // regardless of the locale of the phone. We need to think about 
  // how to allow comma as decimal separator, which will require 
  // updating number parsing and other places that transform numbers 
  // to strings, such as FormatAsDecimal
TODO: allow commas as decimal separator.

Long comments disrupt visual flow. No comment is better than a bad comment.

In Rule 6 (Provide links to the original source of copied code) the article says:

> People copy a lot of code from Stack Overflow questions and answers. That code falls under Creative Commons licenses requiring attribution. A reference comment satisfies that requirement.

This is incorrect (or, more accurately, not enough). The license is CC-BY-SA: the BY part requires attribution, but the SA part also requires that you share your own code.

I write comments first, then fill in the code later, adjusting the comments as I learn better ways to do things. That way, the comments are like a guide to anyone as to the goal of a section of code. I comment about every 2 or 3 lines of code, or more sometimes. I even comment on things that everyone would easily understand. My comments are basically a plain English version of the code. Functions and such have comments or docstrings that explain the function and the basic steps of its functionality, so that’s about 2 times that I explain things in my code. I’ve never had anyone say I comment too much. When reading uncommented code, I wish there were more comments sometimes to explain what each variable does or is. My variables are often named with 4 or 5 words, connected by underscores or title case. I often see variables that aren’t named well and try to avoid that myself.
Are you concerned that you are introducing tech debt into the codebase? Anyone who refactors your code later will also have to refactor your comments (but likely won't).
If they don’t refactor my comments then that’s their lack of care, I’m not responsible for that even a little bit.
I like these rules but if I were writing my own set the first one would be that the most important comments you write are often those describing persistent mutable state. Often the point of keeping an objects members private is to preserve the parity among them and you explaining it where they're declared can save everyone a lot of trouble. Also if you've got a state machine the semantics of all the different states.