4 ms·
It's just a rule of thumb, like anything else. In most code, "why" is the hard part; I see that you are incrementing that account by a penny from out of the blu
by jerf 2y ago
It's just a rule of thumb, like anything else. In most code, "why" is the hard part; I see that you are incrementing that account by a penny from out of the blue, but why? When you are in code where "what" is the hard part, like an implementation of a book algorithm or some tricky performance optimization, then by all means comment that.
Really all this rule amounts to is
// Increment by a penny
accountValue += 1
is a pointless comment, please don't do that. Schools had a way of accidentally teaching that by too-rigidly requiring "commented code", in situations where there wasn't much else to say, or situations where the students themselves didn't necessarily have a strong sense of "why". Any comment that isn't just literally "this is what the next line does" is probably useful to somebody at some point.
- maeln 2y agoI do agree that documenting the why is way more important than the how/what. But having a short comment to summarize a block of code like: // Parse the filename and remove the extension let fext_re = Regex::new(r"(.\*)\.(.+)$").unwrap(); let page_cap = fext_re.captures(fname).unwrap(); let page_base_filename = page_cap.get(1).unwrap().as_str(); Is still useful. Instead of having to read the next few line of code, I already know what they are suppose to do and expect. It makes discovery, later down the line, easier.
- thwarted 2y agoThis would be entirely self-documenting by replacing that with a function named after what it does, then the comment isn't necessary. To boot, a unit test could be written that would reveal the bug in the regular expression that makes it only work with filenames that have an asterisk before the extension. Unless you intended that (unlikely), in which case the comment is wrong/not comprehensive and misdirects the reader.
- jffhn 2y agoYou can put these comments into the name of a function, getting rid of the redundancy and having them read by whoever would just be reading the code not to be distracted by the comments.
- meindnoch 2y agoIf you didn't name you variables "fext_re" or "page_cap" you wouldn't need that comment to explain what the code does.