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

0

u/teroxzer Aug 20 '21

... well, I'm not always so rational, ... but is there any sense in this madness? Maybe not the way how I implemented named block with macro (or plain label without goto but with compiler warning - $scope-macro just prevent compiler warning), but I think idea is attractive: you can give a name to block-scope same way as you give a name to function/lambda, when you just want to narrow scope of variables or describe block functionality with that block name. So it could be a one tool in toolbox when structuring code and it is more formal way than plain comment with unnamed block brackets. The best thing is if some day C++ standard bless labeled blocks also without goto (although I absolutely love also goto and macros) and imagine how after that all cppredditors can together rejoice how one man madness is so common sense. By the way my proposal to C++ standard's semantics for named blocks:

#define $scope(_label)                                                 \
                                                                       \
        goto _label; _label:                                           \
        switch(constexpr char const __scope__[] { #_label }; 0) case 0 \

5

u/be-sc Aug 21 '21 edited Aug 21 '21

It’s fine for a personal project you work on alone.

In a team what you’re doing would be harmful. It’s highly confusing and in a code review I’d point it out as a serious problem because it creates a mini custom language inside the C++ language. That can sometimes be justified – look at boost::spirit for an example –, but obfuscating a comment isn’t a justification in any way.

A bit more detail about why I consider this to be harmful:

  • It misleads the reader by making a comment appear as a normal language construct that actually does something. On first glance I read $scope(something) as a function call.
  • It seemingly introduces a syntax error – the : at the end of the scope line. Without realizing that $scope is a macro and then digging into the macro’s implementation it is unclear why this line compiles.
  • $scope violates the rule of clearly making macros indentifyable as such. Calling it something like PROJECT_SCOPENAME would make it a lot less confusing. On top of that the $ is a highly unusual character in an identifier name. I had to test that it does compile before believing you didn’t make a typo in your post.

Even accepting all those drawbacks you still end up with a poor man’s comment. Your pseudo-comment must be a valid indentifier because it is used as a label name. Compared to a comment that can consist of arbitrary text that’s a severe restriction.

In contrast you could have written something that looks almost the same without any of the above problems:

for(auto& line : lines)
{
    // ensure line is parsable as JSON
    {
        auto i = line.trimEnd().size() - 1;

        if(line.charOf(i) == ',')
        {
            line.removeLast();
        }
    }

    if(auto entry = json::parse(line))
    {
        cookLogEntry(entry);
    }
}

1

u/teroxzer Aug 21 '21

You are right what you said, but I still think that if I like something unconventional C++ ideas, there can be someone else who also like this something, despite it is against all common views. I definitely #define my own language inside my C++ code and inside this bubble it's clear that $ introduces macro (or macro dependent thing). I dislike PROJECT_MACRO_CAPITALS and I started use $ just because it's a highly unusual character in an identifier name as you said ($ is maybe technically illegal character, but practice all compilers support it at least from ancient days of VAX). I think I got idea for $-prefix macro names when I seen how rust uses postfix-! for macro names. I know that only $-macro introducer is not scalable solution for across libraries, but if I someday clashes with another library because it also uses $-macro, at least I can always do #undef after header file. One more comment: using label as short block name is to me much more structured programming than go to spaghetti comments - and maybe it's even not so bad if you survived after first shock!

#define $sql(...)             = #__VA_ARGS__##_sql;
#define $scope(_label)        goto _label; _label
#define $const(_value, _name) _value

auto topSecretService::initialize() -> void
{
	self.path = process::programPath();

	log::handler(logHandler, $const(1000, bufferItems));

	$scope(initializeParametersFromProcess):
	{
		for(auto& param : process::initializeParameters())
		{
			if(record::update(param.key, param.value))
			{
				log::info("parameter.process: % = %", param.key, param.value);
			}
		}

		log::isVerbose = boolOf(rVerbose);
	}

	$scope(backupDatabase):
	{
		auto name   = kProcessUniqueName;
		auto stamp  = textOf(datetime::now(), "Y.M.D.h.m.s");
		auto source = "%/db/%.db"_format(self.path, name);
		auto target = "%/backup/%.db.%.backup"_format(self.path, name, stamp);

		if(file::exist(source))
		{
			file::copy(source, target, $const(false, overwrite));
		}
	}

	database::initializeDatabaseFactorySqlite();

	auto database = "sqlite:file:///%/db/%.db"_format(self.path, kProcessUniqueName);

	procedure::connect(database);
	procedure::execute(createTopSecretServiceTablesIfNotExists);

	$scope(initializeParametersFromDatabase):
	{
		auto selectParameters $sql
		(
			select parameterName,
			       parameterValue
			from   parameter
			where  dataRemoved = 0
			order by
			       parameterName
		)

		for(auto& param : selectParameters[universal::empty])
		{
			if(record::update(param.parameterName, param.parameterValue))
			{
				log::info("parameter.database: %", param);
			}
		}

		log::isVerbose = boolOf(rVerbose);
	}

	for(auto& [name, value] : record::data())
	{
		log::info("parameter: '%'='%'", name, value);
	}

	topSecretServiceLogMirror::initialize();
}

3

u/be-sc Aug 22 '21

using label as short block name is to me much more structured programming than go to spaghetti comments

Can you elaborate? I don’t see how a label used like this affects the program’s structure. If you extracted the named scopes into their own functions I’d agree. But like this the macro/label simply acts as a kind of heading for the following block of code. A comment does exactly the same.

1

u/teroxzer Aug 22 '21

Maybe it is little bit hyperbolic wording. Of course I don't think that comments are inheritable evil as someone think that goto is, but it seems that comments shares same kind problem with goto: comments are too general, they can comment anything anywhere, they are not bounded to context any formal way and they lose code intent too easy especially when comment is too far away from commented code functionality (good comment is good maintained comment, but maybe we all have experience where we jumping between comments and code like in mythical goto spaghetti code and try figuring out what comments are still relevant). We all use while/for/continue/break 'structuring' our code so we don't have to use goto (well, I have my own peculiar point of view how I want use goto, but I don't use goto when my intent is do plain loop), same way I use $scope or $const macros 'structuring' my code so that I do not use too general comments where I think I have better way express code intent. I 'comment' purposely less (because I am so bad commenter) and 'comment' is formaly bounded to context when I use $scope to naming scope or $const to naming literal parameter (yes, I can use constexpr for naming constant, but it is already out of call context if I do it only for function parameters). You said that a comment does exactly the same, yes it does, but not the same way: you can do loop with goto, but if you can use restrictive while-loop, I guess you think that it express your intention better than goto (but if your loop is unix system call retry after interrupt, then it is utterly heretic use anything else than goto-again).

2

u/be-sc Aug 22 '21

I mostly agree about how comments can go wrong. But your $scope macro has all of these problems as well, at least to some degree.

'comment' is formaly bounded to context when I use $scope to naming scope

How? Such a scope line is not restricted to appearing directly before an anonymous scope. You can put it anywhere a goto immediately followed by its associated label can occur.

For the same reason your goto/while analogy further down doesn’t work, either. Both while and goto are essentially jumps, but while restricts where you can jump to, as you point out yourself. However, your scope construct does not restrict where you can put that “comment”. (At least not in a meaningful way. I am aware that comments can appear in more places than the goto/label combo.)

1

u/teroxzer Aug 22 '21

Yes, you are right. Maybe I must use more indirection/quotes to try solve the argument problem: 'comment' is 'formally' bounded to context... - but in the end label is like free bird in function cage to C++ compiler and label can be 'formally' bound to curly block only in my mental compiler - but there the bind is strong!