4 ms·
> Comments should explain the why, not the what or the how. Obviusly that are exceptions, almost all of them around the really algorithmic parts of the code, so
by slightknack 6y ago
> Comments should explain the why, not the what or the how. Obviusly that are exceptions, almost all of them around the really algorithmic parts of the code, something I have to write less than once per year (backend software is not that clever.)
Although I agree that choosing clear variable and function names is usually enough to explain what code does, I'm just not entirely convinced that concise code becomes harder to read with multiple people or after coming back after some time. I feel that communication and documentation is generally the best way to get someone up to speed.
By concision, I mean something closer to terseness or brevity: exactly enough to understand what's going on, without anything superflous. Here's a classical concise python one liner:
def flatten_list(t):
return [item for sublist in t for item in sublist]
This flattens a list of lists into a list. But if you're actually coming back to the code either having never seen this comprehension or forgetting how it works, a little comment never hurts:
# iterates through each sublist to flatten a list of lists into a single list
Some may say this is redundant, but it's useful in more complex circumstances too. If you're working on a machine learning pipeline, say, it can be a quick way to block out some code.
# normalize all the input data
# generate embeddings
# train until error doesn't improve for 100 epochs
# run the net on our test set
(This is my third most favorite programming trick: pretending that something exists, then building it out*)
These examples are besides the point though. Terse code doesn't have to be illegible or hard to comprehend; it's all about finding that balance: no less, no more.
* My second most favorite programming trick is building a small set of tools and using those to redefine the problem.
> If it's not enough probably those functions are doing the wrong thing, maybe more than one at once, and must be redesigned.
Often I'll come across old code, think, "this can be written much more efficiently if I do it like this" and then half way through refactoring remember that I did it the first way because I already thought through the problem and realized that the first way was better and but wait maybe if I do this then that and so on...
It's easier to leave a quick comment just explaining why code is the way it is, which is all I was suggesting.