Unit 02.00: A comment earns its place by saying why
A comment that repeats the code is worse than no comment, because it also has to be maintained.
Comments carry what the code cannot
Code states what happens. It cannot state why that is the right thing to happen, what the data means, or which decision you weighed and rejected. That is the whole job of a comment.
So # remove values over 5000 beside a line that removes values over 5000 adds nothing. # 9999 is the ward system's not-recorded sentinel adds everything: it tells the next reader that this is missing data wearing a number, and that treating it as a value would be a factual error rather than a stylistic one.
Naming the sentinel as a constant helps too. NOT_RECORDED reads as meaning; 9999 reads as a magic number.
This block shows what the comment is protecting against.
# A comment earns its place by saying WHY.
visits <- c(412, 455, 388, 401, 9999, 498)
# Bad comment: "remove values over 5000" -- the code already says that.
# Good comment: 9999 is the ward system's "not recorded" sentinel, so it is
# missing data, not a busy day. Averaging it in moves the mean by about 1600.
NOT_RECORDED <- 9999
clean <- ifelse(visits == NOT_RECORDED, NA, visits)
cat("With the sentinel :", round(mean(visits), 1), "\n")
cat("Treated as missing :", round(mean(clean, na.rm = TRUE), 1), "\n")
cat("Difference the comment explains:",
round(mean(visits) - mean(clean, na.rm = TRUE), 1), "\n")
The mean with the sentinel included is 2025.5. Treated as missing it is 430.8 — a difference of 1594.7, on six values. The comment is not decoration; it is the only thing in the file that explains why the second number is the true one.
The mistake this prevents
The mistake is commenting the mechanics and leaving the meaning undocumented. Six months on, the mechanics are readable from the code and the meaning is gone.
Takeaway
Write comments about data meaning, business rules and rejected alternatives. Give sentinel values names. If a comment would be obvious from reading the line beneath it, delete the comment and improve the names.
