Afonso de Gouveia

← Development

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:

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.