When To Write Code Comment ?

comments-in-codeContinuing this week topic on code comment. When should a developer comment their code ?

Explain why

Now, it is not always possible to write readable code. So, code comment should be written when readable code is not self explanatory enough.

Comment should also be written to explain the “why”. The key is “why”. Comment should explain “why” the code is written in certain way. Never how the code works. Because every developer knows how the code works.

Logic Choice

Sometimes in programming an application, a certain logic is chosen because it is the most suitable solution to the problem. It may be because it is more efficient or it is easier to understand.

Reasoning

Code comment should also be written at the top of the file to explain coding standards used in the application, especially in  library files.

By explaining the reason behind the code, new developers can quickly understand the code.

Refresh

It also serves as a refresh for old codes. Imagine looking at 5-year old code. With the rapid advance of technology. It is possible that there exists a new and better solution. By looking at the old code comment, we can see if the new solution is indeed better.

Code comment should be written together with the development of the actual code. Either before the code is written or after the code is written. This is while the logic is still fresh.

Old code comment should also be refreshed whenever there is a change in the logic of the code.

When do you write code comment ? Share with us in the comment section below.