Rules for Code Comments
- only document the "why". The code should be documentation of the "what" in most cases
- if you had to rewrite a piece of code 3 times before it worked, write about what made it so difficult
- if you had to google or read documentations for a day before a piece of code worked, write about what made it so difficult and link the documentation/stack overflow result
- if a piece of code is much more complex than expected (Bullshit detector) write about the reason (or better: rewrite it)
- if you had a profound insight or learning while writing some code, leave a comment about it
- write about edge cases, that are easily missed
- include links to external resources
- comments are often read by people who have no idea about the context (this even might just be you in a few years), so make sure to provide context (links, your name, date)
- if you are having trouble reading your own code, document it (or better: rewrite it)
- only comment as little as possible, as much as necessary
- comments become stale and old -> do not document rapidly changing pieces, only code that has settled
- docstring (
/* @param ... */
) for stable APIs
- docstring (
- Tests can be documentation: a working example of how to use the API
- Leave a (3-5 line) summary of what a module does at the top of it. This is much better in most cases than line-by-line or function-by-function comments
- From comments on video DON'T Comment Your Code (youtube.com): comments should
- identify dependencies that are not apparent
- describe reasoning for architectural choices
- significantly reduce surprise
The comments inserted by AI tools are usually not useful, since they just explain what the code is doing - which is mostly trivially obvious when you read it. You should not copy this style:
// List of options to populate the dropdown
const optionsList = ['Option 1', 'Option 2', 'Option 3', 'Option 4'];
// Function to populate the dropdown
function populateDropdown(options) {
const dropdown = document.getElementById('dynamicDropdown');
// Clear any existing options
dropdown.innerHTML = '';
// Create and append options
options.forEach(optionText => {
const option = document.createElement('option');
option.value = optionText.toLowerCase().replace(' ', '_'); // Example of setting value
option.textContent = optionText;
dropdown.appendChild(option);
});
}
// Call the function to populate the dropdown with the list
populateDropdown(optionsList);