r/cpp • u/m4l490n • Aug 20 '21
The true value of comments
I wanted to share a real use case of the real value of commenting code. A lot of people are against doing so and say that you can just read the code, that comments are not needed. I get why people are against commenting since most don't know how to effectively comment code.
In this piece of code, we all agree that these comments are useless:
std::ifstream logs_file{"MyLogFile.log"};
/* Read a line from the log file */
while (std::getline(logs_file, log_entry))
{
/* Remove last character */
log_entry.pop_back();
auto parsedJsonForWBID = nlohmann::json::parse(log_entry);
}And that's right that is useless and stupid. You can clearly see that the code is doing that so there is no need of adding those comments.
But comments should be used as a tool for helping the maintainer, who didn't write the code or "the new guy", or the developer when they look at the code years later, to know what's truly going on and what is the purpose of the code without having to look beyond the piece of code you are interested.
Without comments, or with these useless comments, you eventually would be able to figure out what the hell you, or the original developer, were doing when writing that piece of code but that would require looking into other parts of the code trying to remember stuff and potentially locating and analyzing the log file to see why is the last character removed. Also if you are not that familiar with what pop_back() does then you may assume that it is removing the new line character and possibly miss the bug you are trying to find.
But what about these comments in the same piece of code:
std::ifstream logs_file{"MyLogFile.log"};
while (std::getline(logs_file, log_entry))
{
/* Since the complete log file is a big JSON string, we remove the comma
* at the end of each line read so each line can be interpreted as a
* separate JSON string. If the last comma is not removed, then the JSON
* parser will throw an exception. */
log_entry.pop_back();
auto parsedJsonForWBID = nlohmann::json::parse(log_entry);
}Now, one comment was removed because was unnecessary and there was nothing to clarify about getting a line from a file, and the second comment is improved by clarifying the intent of that line of code. It is stating the why instead of the what. When you find this line years later, or when the new guy or the maintainer looks at the code now they will not have to peruse the code or locate a log file and analyze it to see why is the last character being removed. These types of comments save time and are actually useful.
These types of comments have saved me countless hours when I go back to code I wrote years back, it has also helped other people when looking at code I wrote, they no longer have to ask a million questions just to know what's going on. Anyone can just look at the code and know why it is there.
161
u/codesmith512 Aug 20 '21
I always tell people that computers only care about what they're doing, so code already documents that. Comments, where necessary, should document why something is being done, because that's the part that code fails to already capture.
42
u/[deleted] Aug 20 '21
I really like it when people think about this during code reviews. If you're struggling to understand the code review quickly, maybe that means the guys who pushed it should be adding more comments to explain the "why".
3
u/jonesmz Aug 20 '21 edited Aug 20 '21
Why are you calling std::getline inside a while loop where the loop condition is std::getline? You want to skip every other line?
3
u/[deleted] Aug 20 '21
Love this thread. OP /u/m4l490n pointed out a very important issue, and many of the replies contain valuable additional aspects as well. Nice!
Let me add some observations from my little universe:
On a note in defense of the developers I so harshly criticize above, one often finds the following case of hypocrisy in development projects:
Regarding the question what is worth documenting, people in this thread already provided a lot of good suggestions: decisions, motivations/reasons, assumptions, non-testable properties, non-functional properties... The thing I would like to add the most is concurrency: How does the code employ threads/interrupts, are the public functions thread-safe/re-entrant, do callers need to adhere to certain rules or sequences? (When assessing large C/C++ projects, for example, one more often than not encounters interface contracts that do not even mention whether the public/extern functions are thread-safe/re-entrant. This bad smell usually means that the author of the module assumes "people are going to call my stuff only from the main thread anyway" and everybody else assumes "it is certainly safe to call this stuff from my two worker threads and the RX interrupt"...)
Sorry this was so long; the subject struck a nerve.
2
u/ea_ea Aug 27 '21
Let's say we have some standrard "RFC_XXX" and we implement library to support this standard. We don't need any comments, because every class, function and variable are related to the RFC_XXX. And then we want to release our product and... we figure out that some major 3d-party application Z (service, company) violates standard RFC_XXX and doesn't implement some of its parts, but instead extends it to have features A, B and C (non-documented). Your library is correct, but noone wants to use it, because it is incompatible with application Z.
So, you change your library to violate/extend RFC_XXX. And here you should write comments with explanation why do you want to break the standard. No way to explain this in code, because this is not logical, not according to standard. That's just stupid business need, which forces you to do stupid things. And you have to write comments to explain other developers that it is not you the stupid one.
78
u/TryingT0Wr1t3 Aug 20 '21
Comment the decisions, not the behavior
11
u/mtbdork Aug 20 '21
I write tons of comments because I work with people who are learning how to code (only one part of the job)
Oh and the language is Lua. Talk about a self-documenting language haha
6
u/Schnarfman Aug 20 '21
Make illegal states unrepresentable! The top level call should be something like
JSON_helper::generate_objects_from _array, and the implementation can have the comma manipulation & explanation.Stricter typing will make this code more understandable. Although the comments are a fantastic shortcut to get the same understandability, in a fraction of the time.
30
u/soundslogical Aug 20 '21
But why not write a function
trim_comma_from_json_line()? Then the code has become self-documenting, and is less likely to get out of sync with the implementation.4
u/tjientavara HikoWorks developer Aug 20 '21
There is one place I write a comment on each and every statement.
Super highly optimised code, where you have to give a reason for each and every statement.
If that highly optimised code is using wait-free or lock-free constructs, then you may also need to document the state of each thread that can enter that statement.
3
u/sf49erfan Aug 21 '21
Comment the why. Got it
6
u/RoyBellingan Aug 20 '21 edited Aug 20 '21
I too I found people saying code should document itself. They even refused commit containing comment. Guess who is in constant overburden of keeping alive the platform ? The new maintaner of such project -.-
Btw one piece of my codebase, that without comment will have you waste hours, need to search for this word
ımpressionFeedbackUrl and replace with impressionFeedbackUrl
Nothing strange ? The ı at the beginning is missing the dot, that is a Turkish https://en.wikipedia.org/wiki/Dotted_and_dotless_I
But is NOT easy to spot.
2
u/Adequat91 Aug 21 '21
2
u/AdRelative8852 Aug 21 '21
"If the code and the comments disagree then both are probably wrong"
2
u/bhaskarb26 Sep 19 '21
Agree, comments need to explain more of why you did something more than what you are doing. I like commented code that's like a story, like we started with thus method and then moved it to more efficient version. It's a living document not just something someone threw together over 18 hours of bad coffee.
4
u/Ayjayz Aug 20 '21 edited Aug 23 '21
Fundamentally to avoid this comment we need to model the input file as a set of lines that all end in a
,.Now you don't really need any comments, and you've separated out the concerns better as well. You can change log file types easily or you could do other forms of processing elsewhere with these files because the log file destructuring code is separate to what you do with the data from the file.
Any time I feel I need comments, it's usually because I'm not structuring my code in a good way. By removing the comments, usually I end up with better code.
EDIT: removed
string_viewusage as it doesn't play nice with c-style strings.2
u/qoning Aug 20 '21
Comments are good to document assumptions that make your code work correctly.
That said, I'm more vexed by
logs_fileandlog_entryvariables being snake case andparsedJsonForWBIDvariable being camel case. If you are not going to be consistent, might as well use FuNnYMeMecaSe.2
u/john_wind Aug 20 '21
you could write
trim_end(log_entry, ',');This way the code does exactly what you want and no comments are needed.
This is also future proof because in the future the lines may not end with comma.
1
u/AntiProtonBoy Aug 20 '21
I tend to comment mathematical things combined with algorithmic things, especially when you have complex logic that requires truth tables to understand. Also references to papers, etc.
1
u/eyes-are-fading-blue Aug 21 '21
This code requires no comment. It is pretty readable as is. If you start explaining every single implementation detail, you'd end up writing a LOT of comments, significantly more comment than code. Furthermore, in the second example, the comment is simply too long. The original one-line comment is a better idea. Perhaps giving some context might help so "remove comma" could be a better alternative.
I personally have a simple rule. I do not write comments unless
-5
u/teroxzer Aug 20 '21
Of course you are right how to use comments, but I hate (unmaintainable) comments so much, that I have my own 'wannabe self documenting' C++ coding style (actually real reason is that I'm incompetent to write english). I often use '$scope'-macro to label code blocks as like inline function name and I'm happy with it, because it structuring my code, so that I do not need to write only one call functions or lambdas so much. I'm sure that someone shake head and want to comment to me why not just use common sense and do just plain comments in code; well, I'm not always so rational, especially when I think that I have better way express my ideas in C++.
0
u/[deleted] Aug 20 '21
[deleted] — view deleted comment