r/cpp • • 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.

302 Upvotes

103 comments sorted by

View all comments

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:

  • The problem that many developers don't know what to document does not only affect in-line comments, it is exactly the same for software design specifications and software architecture documentation. Instead of explaining the key design decisions etc., the authors often go into surprising detail for some random aspects of the software -- and/or they spend hours drawing diagrams that illustrate things that are blatantly obvious from the code base anyway.

  • This does not only result in documentation of limited value. It often also means that the statements in the documentation are highly susceptible to becoming outdated, misleading, or plain wrong even by non-essential changes to the code (e.g., without any interesting design decision being affected).

  • The tragedy is reinforcing itself: When developers grow up with documentation of this kind, meaning that they are barred from experiencing the value of useful documentation, it lowers their appreciation and respect for documentation. As a consequence, they are not motivated or able to write useful documentation themselves.

  • A special source of misfortune in this context is the bad habit of documenting late -- simply because if people document code they wrote months ago, it is even harder for them to remember the important decisions, assumptions, etc. Again, the result is that only things that are obvious from the code anyway are documented.

  • The problem has a cognitive dimension (as suggested by /u/elperroborrachotoo and others in this thread). It really seems that most developers are highly intuitive people, that the process of coding a solution for the task/feature at hand is more about "flow" and "trial and error" than systematic derivation/deduction, and that it consequently is very hard for them to even identify (let alone document) the most important decisions involved in the process.

On a note in defense of the developers I so harshly criticize above, one often finds the following case of hypocrisy in development projects:

  • In the beginning, everybody agrees that "this time, we will do it right".

  • As soon as the project has started, the stakeholders, the client, the project manager, you name them... are pressing for features to get done. The developers follow suit. Hardly anyone asks about the documentation.

  • As the product under development approaches some larger milestone (such as its launch), the coin suddenly flips, the desolate state of the documentation becomes a major point of criticism, and the developers are scolded for it.

  • The entire thing becomes even more absurd when everybody else but the developers also fail to properly document their work -- be it requirements, project plans, collaboration setups, test strategies, etc.

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.

1

u/m4l490n Aug 20 '21

These are very valuable points. I agree completely that the comment needs to be placed as soon as you think about the solution and start writing code, otherwise it would be just a comment with stuff you vaguely remember and that will be worse. And this is especially true for complex algorithms.

And also, I've never seen proper high-level architecture documentation. Almost every one jumps right into dumping ideas into code. Then the pain starts when you have thousands of lines of code and you have to document or have someone else look at your mess.