Maybe Comments _Should_ Explain 'What'

https://news.ycombinator.com/rss Hits: 15
Summary

People say “ should explain why, not what.” I feel like starting a flame war today so I’m going to argue that comments should explain ‘what’ too. Please don’t use this as justification to write bad code, okay? Okay. First of all, why shouldn’t comments explain ‘what’? If you need comments to explain what’s going on, it suggests your code is unclear. If I write //weight, radius, price w = 10, r = 9, p = 1 That’s not as clear as saying weight = 10, radius = 9, price = 3 “But it’s obvious that w is weight!” Sure, if you’re seeing those lines back-to-back. But presumably you’re initializing the variable to use it, which means that it’s going to appear later. When you see w later in the body, you need to go back and check what it is. That’s a frustrating context switch and you may skip it, possibly assuming that w is… width. Then bad things happen. So comments are not a substitute for clean code. Okay, so why should comments explain why? Some people argue that we should instead store the ‘why’ in commit messages or tests. Most people feel icky about this, though. Given: // Clear twice to deal with bug ABC in library XYZ, see [link] XYZ.clear(); XYZ.clear(); Would you prefer that comment be removed and placed in the commit message? Then if you want to learn why XYZ.clear() is repeated twice, you have to dig up the commit. That can be a difficult and tedious job, especially if the line was reformatted, moved between files, anything that makes git blame not work. Searching all that is a context switch and you may skip it, possibly assuming that it’s a bug you can remove. Then bad things happen. Both of these cases share the same problem: looking things up is hard. Best case it’s a context switch that takes time away from understanding the problem. Worst case you don’t look it up and make a potentially-dangerous assumption. It’s better to keep the information in the exact same place that you need it, whether that’s via descriptive code or comments over commits. Now for the w...

First seen: 2026-01-04 12:20

Last seen: 2026-01-05 02:22