Write readable code
Everyone agrees that we want to write understandable code. Whether it's you returning to your code two weeks later or a newcomer reading it, the easier it is to understand, the easier it is to expand or fix. Most importantly, the work goes faster and costs less.
What should I comment?
The end goal
In delivered code, comments should only be found in these circumstances:
- A complicated bug was fixed and a line was changed-a comment above it warns what must be considered when changing it.
- A complicated implementation can't be simplified further and may be misunderstood during maintenance-a comment warns what must be considered when changing it.
- At the top of a public method or class-these should have top-level documentation of expected behaviour and potential gotchas.
- At the top of a very complicated method that can't be simplified further-give a high-level description of what it does and its use case.
During implementation
Write as many TODO comments as you need to describe the logic of what you need to do, then remove comments as you consider each section readable enough without them. This helps you follow the logical behaviour of the feature you're implementing.
Write a TODO comment describing behaviour to implement and implement it below the comment. Once done, ask whether you can easily understand the code without the comment. If not, extract the code into a separate method whose name and documentation act as your comment, or adapt the comment as needed.
Try to delete your comments
A good exercise is to compare how readable your code is after removing a comment. If removing it makes a section hard to understand, perhaps move that code into a separate method. The method name then describes what it does and the original code becomes easier to read.
Explaining why
The most logical comments to keep are those that explain why you wrote the code. What the code does should be clear from reading it, but why it exists is less straightforward, which increases the value of comments that explain it.