When does a comment help?
- MDN:
If the purpose or logic of the code isn't obvious, add a comment with your intention
source
How does a comment stay true?
- PEP 8:
Comments that contradict the code are worse than no comments. Always make a priority of keeping the comments up-to-date when the code changes!
source
What about code you commented out?
- ABAP:
Deleted code can be reproduced from the version history later on.
source
How does a comment start and end?
- C#:
Begin comment text with an uppercase letter. End comment text with a period.
source
Do parameters need tags?
- Kotlin:
Generally, avoid using @param and @return tags. Instead, incorporate the description of parameters and return values directly into the documentation comment, and add links to parameters wherever they are mentioned.
source
Where does a comment go?
What do cluttered comments look like?
// get the user
const u = await getUser(id);
// check if u is null
if (u === null) {
return;
}
// loop over the items and add up
let t = 0;
for (const i of u.cart) {
t += i.p; // add price
}
// let t2 = t * 1.18;What does the code look like cleaned up?
const user = await getUser(id);
if (user === null) {
return;
}
// Prices are whole paise, not rupees with decimals,
// so adding them up never rounds.
let cartTotalPaise = 0;
for (const item of user.cart) {
cartTotalPaise += item.pricePaise;
}What changed?
Where next?
Each languageās rules: clean code by language.