The unrelated picture is our garden. 2017 was a good year.
When do we add comments to our code? To us, comments answer questions that a reader cannot already answer. Here are our guidelines (others' ideas follow).
Add comments to public APIs. Explain what the method/function/property does. This provides value to users who do not have immediate, easy access to the implementation source. It also populates Intellisense.
Add comments to unusual code. Explain why the code is doing something unusual. This provides value to future developers who are changing the source code in the future.
Avoid adding what or how comments to private code because:
- They provide little value. If we are writing methods, functions, and classes that are single purpose, concise, and readable, then a comment will provide little additional value. If not, our effort would better be spent refactoring.
- They take time to write. It is hard to capture in English what we have already expressed precisely in code.
- They take time and discipline to maintain. When the code changes in the future, we need to update the comment, otherwise the comment will be wrong and mislead future developers.
Writing expressive code is much like writing a how-to essay. A module contains the main organizing idea (similar to the thesis statement.) Each function/method expresses something about that idea (similar to a paragraph). Each function/method implementation keeps the promise of its signature (much like a paragraph body keeps the promise of its topic sentence.) Writing code is like writing a how-to essay that both a machine and a human can understand.
Not everyone agrees with our guidelines. Here are some other ideas that colleagues give:
- Adding what and how comments to private code can provide tremendous value to helping new developers on-board to the code base.
- Adding what and how comments to private code keeps information in sync across teams.
I'd love to hear other ideas on Twitter/Slack/email...