The reason we mention comments here is that comments are often used as a deodorant.
🚨 Problems
Comments are usually created with the best of intentions, when the author realizes that his or her code isn’t intuitive or obvious. In such cases, comments are like a deodorant masking the smell of fishy code that could be improved.
function printOwing(invoice) {
printBanner();
let outstannding = calculateOutstanding();
// print details
console.log(`name: ${invoice.customer}`)
console.log(`amount: ${outstanding}`)
}
âś… Solution
When you feel the need to write a comment, first try to refactor the code so that any comment becomes superfluous.
If a comment explains a section of code, this section can be turned into a separate function via (1) Extract Function
. The name of the new function can be taken from the comment text itself, most likely.
function printOwing(invoice) {
printBanner();
let outstannding = calculateOutstanding();
printDetails(outstanding);
function printDetails(outstanding) {
console.log(`name: ${invoice.customer}`)
console.log(`amount: ${outstanding}`)
}
}
If the method is already extracted but you still need a comment to explain what it does, (2) Rename it
. If you need to state some rules about the required state of the system, (3) Introduce Assertion
.