Thoughts on commenting code and commenting in the right way
People are often told that comments are very important. Comments are an important part of programming. As a beginner, it is difficult to judge and determine how many comments you should add and what to write in the comments!
This is not set in stone, everyone seems to have different and opposite opinions, so this puts you in a dilemma full of insecurity.
This is my train of thought:You should write as few comments as possible to explain your decision.
Let us analyze this.
Your code should be as self-explanatory as possible.
Some things require more thinking, but even if the code is a bit complicated, as long as the programmer can read and determine 100% of the code function, it does not require comments.
When you need to explain the following, you need to commentwhySpecific instructions or blocks. Is notwhat, Should be inferred from the code. We call it advanced because it is code that we can consider. It is not machine language or assembly language, which is difficult to understand.
Some of your code blocks will need comments to explain other code, orEven yourself,whyYou are doing something special. Of course, this is not always the case, and it is not obvious.
Even after 6 months, if you work in another part of the code base and then come back to that line of code, you probably won't remember all the problems you encountered while editing that code. You may remember that some content was added for 90% of the reason, but there are some other content that you can’t find.
The code is more than just descriptions and comments. Many times, you can see why you want to add a line of code through source control (Git). You look for the line in the Git application, and the line's history will tell you why you or your colleague made the edit 10 months ago. If the Git commit message is useful and detailed, don't "fix the error". This is also a good document, especially in open source projects, where many people can access the code base.
If you are in an interview and ask yourself "Should I add a comment to the sport?" The answer is alwaysYes it is.
They are most likely to judge your comments and code. And what you wrote in the comments.
I certainly will. No matter how great the code guide you have, maybe the company needs to fire you within 3 months, and the next person to succeed you will need to understand your code, because this is the company's asset. They really cannot afford to hire people who are unwilling or unable to sympathize with others who try to read the source code.