This post is an excerpt from a beginner-level Python book I am working on. Though it focuses on Python, the core message is language-agnostic. Additionally, I have generalized some of the more Python-specific sections.
Comments are little notes you write alongside your code. They are used to document your code, stating why it works that particular way or what it accomplishes. Comments are also used to detail what type of input the code expects and its type of output.
Comments are important in any project. Unless the code is blindingly obvious, you need to comment it. The purpose of comments is rather simple: to enable other people (and yourself in six months!) to read and understand your code, what is going on, and why it is happening. In other words, it should describe your code, not retell what it is doing. Comments also allow you to leave notes for yourself in case you have to leave your WIP code mid-session.
Anyone can write comments, but writing good comments is a skill acquired over time. Good comments not only follow all the above characteristics but are additionally clearly written and up-to-date with the code they are describing. There is nothing worse than comments that conflict with the code.
As a developer, you should aim to always write good comments. Love it or hate it, early on your comments will not always meet these qualifications. My code comments certainly did not, as evidenced by this actual comment in some of my own code written four months after discovering programming:
I could add this to the list of exceptions, but I choose not too, because of the next line.
The answer is ALWAYS hardcoded, no matter how the user enters it.
This is a bad comment. Instead of rewriting the entire comment to make it cohesive, I appended the first sentence, making the whole thing awkward and disjointed. I should have spent that same time rewriting the comment to be cleaner and more direct. Do not let this example discourage you from writing comments. You should always comment your code. It should be an integral part of programming, not an afterthought when the code is complete. Doing something as small as writing good comments will make you an infinitely better programmer.
By near-universal convention, comments are written in clear, understandable English. While writing comments in your native language is not an issue, English comment versions, even if they are written in addition to native locale comments, are a plus. PEP 8, the Python code style guide, reinforces this convention using the following statement:
Python coders from non-English speaking countries: please write your comments in English, unless you are 120% sure that the code will never be read by people who don’t speak your language.
No matter your chosen programming language and the surrounding circumstance and code environment, the main thing is to always comment your code, no matter what. You will be very glad you did. 🙂