Hacker News new | ask | show | jobs
by TheoLib 1745 days ago
Comments are "reached for rarely and last". Whatever shortcomings comments have pale in comparison to being faced with and trying to figure out undocumented or too sparsely commented code, which, in my long experience, has been an order of magnitude more prevalent than sufficiently documented/readable code. Heck, even a wrong comment is sometimes preferable to no comment if it at least gives me a clue as to what the purpose of that section of code was at some point in its evolution.
2 comments

I personally strive for code that can be read as a sentence, especially in complicated sections of code.

This sometimes leads to weird intermediate variables which might look superfluous, e.g. intermediates like:

foo_has_at_least_1 = len(foo) >= 1

(not a great example, usually it’s a bit more semantics. than that) but later code using those intermediates reads as english, which can reduce cognitive load when reading the code and obviate comments, and preconditions are more readily verified.

It’s literate programming and I prefer that to long comment blocks like those in some of the examples. All that said, it can be hard to get coworkers into such a habit, especially those who feel brevity and abbreviation is a virtue.

The problem comes not with what the code does but why the code exists in the first place.

The only time I ever feel the need to leave comments is to explain code that doesn't appear to be needed or isn't obvious why it exists. Usually this comes from agreed upon technical debt, short notice requirements with tight deadlines, or some other form of tradeoff.

"We're doing a simple check and throwing an exception here since we have work to introduce a more comprehensive permission system in xyz epic"

or something like

"There's a complicated race condition in xyz so we're doing a simple sleep here since the proper fix involves introducing a distributed lock"

Sure those types of things are cases you want to avoid but unfortunately you occasionally end up there anyway and leaving a short explanation about a compromise is better than ambiguous code that appears to serve no purpose

I dont think that held in the examples or a lot of what I have seen in practice once comments become the norm. Most classes should not need a comment in them at all. Most methods should be self-explanatory. A comment detailing every line of code is a huge smell.