DEV Community

Discussion on: "Do not comment on your code, it should be self-documented". Well... I don't agree.

Collapse
 
jcolag profile image
John Colagioia (he/him)

I've been ignoring this, because I'm tired of the "conventional wisdom (or a straw-man version) says X, but I oppose that" genre of article. However, there are a couple of points to make.

First, as I hinted, nobody really says not to document your code. No (serious) programming language lacks a way to write comments, and several try to shift the focus to the comments, so-called literate programming.

That said, comments are almost universally an admission of failure---the "I don't actually know how this works, so don't touch it" style---or vapid descriptions that have nothing to offer beyond repeating what the code does...or, rather, they repeat what the code did when it was first written, but haven't received an update since then. How much time in your career has reading a comment saved you?

The problem is that "comment your code" implies the latter, inserting comments that follow the code. "This assigns the current total to the total variable." "Loop over the array indices." "Increment i by one." Not only are those comments useless, but they make maintenance more difficult, because someone needs to always double-check to make sure that the comments reflect the code...but you already have the code.

Rather, you want to comment the project, from within the code. For some examples.

  • Why did you write this passage? Specifically, if business conditions change, what changes would lead me to delete the code?
  • Does the code implement some standard, such as an algorithm, a design pattern, or an RFC?
  • What trade-offs did you make in this design? What technical debt did you accrue to meet the deadline? We all need to make expedient choices, sometimes.
  • Did you adapt the code from another source? Does that code require crediting the author?
  • Are there edge cases that the code deliberately doesn't bother to cover? Why?
  • Is there a passage in a design document describing the need for this feature? Other than a ticket, I mean, which your commit message should reference, instead...

If, instead of covering that kind of ground, your comment explains the syntax, though, then you should rewrite the code instead of writing the comment. If the comment explains what the variable name means, rename the variable, instead. Those comment the code, and no developer should be forced to read them...