This is another post in our Code Health series. A version of this post originally appeared in Google bathrooms worldwide as a Google Testing on the Toilet episode. You can download a printer-friendly version to display in your office.
by Shiva Garg and Francois Aube
Comments can be invaluable for understanding and maintaining a code base. But excessive comments in code can become unhelpful clutter full of extraneous and/or outdated detail.
Comments that offer useless (or worse, obsolete) information hurt readability. Here are some tips to let your code speak for itself:
- Write comments to explain the “why” behind a certain approach in code. The comment below has two good reasons to exist: documenting non-obvious behavior and answering a question that a reader is likely to have (i.e. why doesn’t this code render directly on the screen?):
- Use well-named identifiers to guide the reader and reduce the need for comments:
- Write function comments (a.k.a. API documentation) that describe intended meaning and purpose, not implementation details. Choose unambiguous function signatures that callers can use without reading any documentation. Don’t explain inner details that could change without affecting the contract with the caller:
- Omit comments that state the obvious. Superfluous comments increase code maintenance when code gets refactored and don’t add value, only overhead to keep these comments current:
Learn more about writing good comments: To Comment or Not to Comment?, Best practices for writing code comments