Principle 5 Comment Effectively

Comment your code so that it's function is clear. Well targeted comments make it less likely that avoidable mistakes are made when using or updating your code. Colleagues and your future self will thank you.

You Must - Write and maintain accurate comments as you code.

You Should - Think carefully about why you are leaving comments, what to capture, and what belongs elsewhere (in documentation).

You Could - Review old code you have written - are the comments helpful? What would you include next time?

Related Areas: Documentation
Easy to Read Code

5.1 Comment Style

Use comments judiciously and look to your style guide for advice on how to comment.

5.2 What to Capture

Ask yourself: “will I understand this code in a years time?”

Comments should bridge the gap between the documentation and the code. They should be written in plain English and describe the logic and purpose of each chunk of code; i.e. where it fits in and why its there.

5.2.1 What not to Capture

You don't need to describe everything you are doing with the code in a comment. Someone reading the code should be literate in the language. Commenting extensively line by line makes it likely that code and comments will get out of sync when you go back and make changes.

There should be separate documentation for high level questions such as the structure or logic of the analysis. Don't write your plan or QA notes in the comments.

Don't store large chunks of alternate code in the comments. Leave that to your version control system.

5.3 Alternatives

If you find yourself writing extensive comments, or writing more comments than code, consider changing format. There are options such as Jupyter Notebooks, and Rmarkdown for combining analysis and prose.