Tip of the week on justification comments

Posted 2022-03-21

I know I haven't written for a long time, but here's a short post finally.

Core D Development Statistics

In the community

Community announcements

See more at the announce forum.

Tip of the Week

Often, when people post some code asking for help, I'll ask: "why did you do it that way?" This is typically because I see something questionable - not always wrong, but often not right in my experience. An example is the cast keyword. Casts are sometimes necessary, but often indicate trouble. It depends on why it is there.

I know some people get annoyed when I ask this, especially since so often my answer is "don't do it that way, try this other approach instead", which can be frustrating when you must do it this way for some reason. Especially when finding the conversation online rather than being involved live!

But I do think it is an important question with an important answer. Sometimes, the author just didn't know the alternatives are possible, or didn't think of the problematic cases. When that happens, they can learn something new and write better code both here and in the future.

Sometimes, though, there is a reason for the problematic code, and we have to go into the issue of how to get deeper into it. Asking them "why did you do it that way?" means they can demonstrate, in more detail, just what they were trying to do and the thought process that led there. This context helps the rest of the conversation maintain productivity.

I think the answer to these questions should actually be in the code as a comment. Any time you write something at the end of a learning process, jot down some of that process in the code. I sometimes keep commented-out code with a note saying why it is commented (or sometimes without that note... but I regret not leaving that note since there's been times where I look back at something from a couple years ago, ask "why didn't I just do it that way?", see the code, and think "oh maybe I just never fixed the bugs" instead of it being a bad approach entirely). Anyway, I like to leave the comments to demonstrate that yes, I thought about doing it that way, but decided against it or that it didn't work out for these reasons.

This can be especially true when working on code with other people: when someone else touches that code, they're probably going to be tempted to "simplify" or "refactor" it, and if the explanation isn't right there - no, git blame is not good enough since that's too easily out of sight, out of mind - might reintroduce fragility or bugs you avoided before.

Similarly, if you're looking at some program and see commented-out code, don't delete it without understanding why it is there. Perhaps the last author just didn't finish something or changed her mind, but perhaps it was deliberately left behind as a warning to those who follow.