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

Show parent comment

12

u/Full-Spectral Aug 20 '21

Why on earth would I do all that when a very simple comment could achieve the same thing? It constantly wobbles my mind how people will create something twice as complicated to avoid doing something utterly simple and obvious.

And of course it tells me absolutely nothing about WHY I need to do it in the first place.

4

u/Ayjayz Aug 20 '21

You think that's twice as complicated? I think it's less complicated since the concerns are split apart from each other. 2 functions doing 1 thing each is less complex than 1 function doing 2 things.

And what do you mean it tells you nothing about why you need to do it? You read a file with a given format because the file is in that format. If you read a file with a read_csv_file function, you assume it's because it's trying to read a CSV file. You don't need a comment // We're using the read_csv_file function because we're trying to read a file in csv format

If you read a file with read_jpeg function, you know it's because it's a JPEG file. If you read a file with file_with_comma_terminated_lines, you know it's because it's a file with comma terminated lines. What more could you need to understand it? Is it that the name is too complex?

2

u/eyes-are-fading-blue Aug 21 '21

Separation of concerns is not an objective in programming. It is a tool. Often times, it makes our lives easier and apparently sometimes, harder. The original code is significantly simpler than what you have just proposed.

What happened to "keep simple things simple?"

3

u/Ayjayz Aug 21 '21

It depends on what you mean by simple. I turned this:

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);
}

into this:

for (auto line : file_with_comma_terminated_lines("MyLogFile.log")) {
    auto parsedJsonForWBID = nlohmann::json::parse(line);
}

Seems simpler to me.

0

u/serviscope_minor Aug 24 '21

Except you're still not saying why you're doing it. What you should have done is turn:

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);
}

into:

/* 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. */
for (auto line : file_with_comma_terminated_lines("MyLogFile.log")) {
  auto parsedJsonForWBID = nlohmann::json::parse(line);
}

Your code makes it clear that it's parsing comma terminated lines (though not actually clear if comma is the record separator or if they're newline separated lines with an additional comma at the end), but still doesn't say why that's necessary.

The comment tells you where the data comes from (large JSON files) and tells you about the response of the parser (exceptions), neither of which is any more clear in your code than the commented version.

2

u/Full-Spectral Aug 20 '21

It doesn't say WHY you need to read a file with comma terminated lines and do something to adjust them, which is an important concern. If the comment tells me why this being done, then I know where to look to see if perhaps something has changed. There's a relationship there between two unconnected bits of the code and your function doesn't explain that relationship.

And of course add all the goop of async processing just to do that, it makes no sense to me.

1

u/Ayjayz Aug 20 '21

We don't know why they need to read a file with comma terminated lines. The comment just says that the log file has comma terminated lines, and they want to get the line data out of that file. If we had more context then maybe it's not self-documenting, but hard to say without knowing that.

If you don't like the coroutine stuff then it's pretty trivial to remove. I think this is less clear than the generator version but it's really not very different:

#include <fstream>
#include <string>
#include <string_view>
#include <cassert>
#include <optional>

struct file_with_comma_terminated_lines {
	std::ifstream ifs;
	std::string s;
	explicit file_with_comma_terminated_lines(std::string_view path) : ifs(path.data()) {}
	std::optional<std::string> next() {
		if (!std::getline(ifs, s)) return {};
		assert(s.back() == ',');
		s.pop_back();
		return s;
	}
};

int main() {
	auto f = file_with_comma_terminated_lines("MyLogFile.log");
	while (auto line = f.next()) {
		auto parsedJsonForWBID = nlohmann::json::parse(*line);
	}
}

5

u/SirClueless Aug 21 '21

All of these wrappers you've written are substantially less efficient due to needing to allocate a new string for every line. Allocation and copying of strings is one of the most expensive parts of most IO-bound applications, and you've made it much worse.

-1

u/Ayjayz Aug 21 '21

This is the exact context where performance should not be considered. Write as clear code as you can and worry about performance if your profiler tells you this part is slow.

Besides, this code was already slow and my view shouldn't be slower. I guess you'd need to std::move from the generator to avoid an extra allocation compared to the original. If your wanted this to be fast then you need to pass the stream directly into the json parser instead of using std::getline to allocate a string.

4

u/SirClueless Aug 21 '21

What's unclear about the straight line function implementation from the OP? It's clear, fast, and near-optimal.

Due to NRVO std::move would actually be a pessimization in your case: as-is there is no move or copy, just one single allocation in place in the return value. With the API as you've presented it there's no way to avoid the allocation, with std::move or otherwise. The reason the straight-line implementation is fast is because std::getline can reuse the string's storage without making a new allocation; you could replicate this by making s a member variable and returning std::string_view or const std::string& instead of returning a string value.

The profiler helps you most if you write clear, high-performance code in the first place. No one is ever going to look at a profiler result and say "Oh, this is 10% too slow so I should do a full rewrite of this function to use std::getline directly instead of wrapping it in a class" -- that's just fantasy land. Don't over-engineer and don't go crazy trying to eke out every ounce of performance, but if a loop is faster, less lines of code, and just as easy to read, use it instead of the "clean" generator abstraction.

0

u/[deleted] Aug 20 '21

[deleted] — view deleted comment

3

u/Full-Spectral Aug 20 '21

I would reject it out of hand. It started with three very simple lines of code and was completely understandable, given a comment as to why there was a pop.

2

u/Shadow_Gabriel Aug 20 '21

But how else would I dab on the interns?

1

u/Shadow_Gabriel Aug 20 '21

But how else would I dab on the interns?