Comment on your code

Source: Internet
Author: User
Tags using git
This is a creation in Article, where the information may have evolved or changed. Every once in a while, there's always a nasty post on the web, the idea is that you shouldn't write a comment for the code, the only reason it exists is because the code itself isn't good enough. I totally disagree with these arguments. # # Rotten code their point of view is not entirely wrong. No one can say that their code is good enough. The code itself will slowly become bad. Do you know when the code rots the most? When you haven't touched the code for six months! When you go back and read it, you'll be very curious: "What does the writer think?" (So, using git blame to see the history, I didn't think the code was written by myself, because that's your code.) The argument against the annotative is that the only reason for needing comments is that your code is not "clear". If your code is refactored, named, and organized better, you don't need these annotations. Today, when the entire project and problem space is in your head, you will naturally feel that the code is clean, clear, and elegant. However, when six months later, or the CTO just happens to find a very serious bug in the production system, the code may be a little blurry to you when someone has to debug your code in a situation where the supervisor is staring. A piece of code you're so familiar with, trying to understand what other people don't understand, is a very difficult skill to master. However, it has invaluable value and is just as important as the ability to write code in place almost once. In industry, basically no one is a lone Ranger. Even if you are really writing code on your own, you will forget the reason why the code is written or the exact purpose of the core part of the "Engineering Code" late last night. In the future once you leave, your successor will have to understand every little preference and habit that is hidden in your head. Therefore, it is not a bad thing to write a comment that is too superficial even now. Sometimes, it can even bring great help. # # No annotations often cause code to be more difficult to understand some people claim that removing comments will make the code better because it forces you to write clearer code. I don't agree with that because I don't think someone will actually write some of the best code and write some comments to explain the behavior (except '//TODO: This is a temporary workaround, I'll fix it later.) We all write the code that we think is best in terms of external conditions (usually time). The problem with refactoring code to remove annotations is that this effort tends to backfire and produce worse code. A typical example is to refactor a complex line of code, extract it into a separate function, and take a words too literally name. This behavior looks great, but now you've brought a context switch point for the person reading the code. Instead of the real code is a function call, so they have to scroll to the function definition place, remember and control the function declaration and call parameters,and substituting the function return value to the place where the call was placed. In addition, a clear function name can only provide very short annotations. Any comment that requires an extra small phrase cannot (or should not) be summed up in a function name. So you end up with a function that has a comment on it. Indeed, a very short function can lead to confusing and more complex code. If I see such a function, I will search for where this function is called. If there was only one place, I would think, is this a generic block of code that does encapsulate the global logic (such as ' Nametouserid '), or is this function heavily dependent on the specific State and implementation of the caller and does not work correctly elsewhere. As you extract the code into a function, you essentially expose the implementation details to the rest of the codebase, and it's not appropriate to make a hasty decision. Even if you know that this function should not be called by other people, others will call it in some places, even if it is inappropriate to do so. Small function related issues in Cindy Sridharan on [medium website posts] (https://medium.com/@copyconstruct/ SMALL-FUNCTIONS-CONSIDERED-HARMFUL-91035D316C29) is described in more detail. We can even go into the comparison and trade-offs of short and long variable names, but stop there, generally you can't accept longer variable names. Unless your variable name is the full comment you want to write, you will still lose the information and have to add it to the comment. I think we can agree: ' Usernamestrippedofspaceswithdotcsvextension ' is a horrible variable name. I am not saying that we should not refine the code to make them clearer and more elegant. Definitely do this! This is a feature of an outstanding developer. However, code clarity and comments are orthogonal, and well-written annotations are also characteristic of outstanding developers. # # No bad comments The examples of bad annotations given in these discussions are minor errors, except those of the introductory programming course, which are rarely encountered in the actual work. "' javascript//instantiation of an Error object var err" is good, this annotation is very clear, but not very useful. But at the same time, it doesn't really hurt. While browsing through the code, it is easy to ignore it, although some are not. If a developer can have a useful comment that can save me hours of keyboard work, I'd rather be a simple comment like hundred, rather than a comment. I'm pretty sure that no code will say "Dude, this code is very easy to understand, so there's no need to provide any comments." "The reality is exactly the opposite. In fact, I found some code that was seriously missing comments.-Go Standard library. Its code is very good, but in many cases it is a challenge to understand why they are designed if they do not have a deep understanding of their functionality before reading the code. If you can add some annotations that explain the logic and design intent of your code, it will make the Go standard library easier to read. In this article, I mainly discuss the annotations in the implementation code, rather than the usual document annotations for public functions (they are also very good, usually). # # Any comment is better than no comment another example that a counter-annotation person likes to take out can be shown with the following concise and powerful picture (proving its argument):! [Pithy image] (https://npf.io/comments.jpg) Ah, very funny, someone has changed the contents of the bottle but did not update the outside of the label. However, this was a problem 20 years ago, when code reviews were not normally conducted. However, the code review is now very common. If checking for comments and implementations is not part of your code review process, it's a good idea to check your code review process. This is not to say that there will be no mistakes, actually I just submitted a "comment and implementation inconsistency" bug yesterday. Words like "No comment is better than wrong comment" sound right at first, however, when you realize that if there is no comment, the developer guesses the wrong code more than the probability of the error comment, you will change your view. Even if this happens and the code is modified, you can still get valuable information: What the code used to be. The modification is only slightly different from the original, it still accomplishes the basic same function. For versioning and backwards compatibility, how often does the same function change dramatically in function without changing the name and signature? Basically very little. Take the bug I found yesterday, we call ' client. Setkeepalive (60) '. The comment for the setkeepalive function, however, is "the amount of time (in seconds) that the client needs to wait for a specified number of setkeepalive before sending a PING request." It looks great, doesn't it? Know I noticed that the setkeepalive parameter is time. Duration. If there is no other specified unit, 60 this integer will use the default unit nanosecond of Go's duration. Hey, someone updated the function, using the Duration type to replace the Int. Interestingly, it still rounded down to the nearest number of seconds, so the comment was not incorrect, just a bit misleading. # # Why? The most important comment is why you want to comment. Why is the code executed according to design? Why does this ID need to be less than 24 characters? Why hide this option under Linux? Such. The reason why these problems are important is that you cannotExtracted from the code. These annotations summarize the lessons learned by developers, business or system-level constraints, and so on, which are of immeasurable value and are almost impossible to obtain from other sources (for example, a function name should reflect what the function does rather than why). Annotations that describe the functionality of the code are often not particularly useful, because if you have enough time and effort, you can always understand the functionality of the code. In essence, with function definitions, the code will often tell you about its specific functions, but that doesn't mean you shouldn't write any comments. You should strive to write the clearest and most concise code, but the annotations do not require any additional runtime overhead, and if you feel that someone is having trouble understanding some code or understanding, you should write some comments. At the very least, this will save them half an hour to understand your code, and these comments will help them to avoid the wrong modification or use of your code, causing bugs to occur. # # Test Some people think that functional test cases for functions are equivalent to documents. In a way, that is true. However, in my Efficiency document table, it has a very low priority. Why is it? Because they are extremely precise and trivial, they only cover a very small part of the function. Each test tests only exactly one specific input and the output that matches it. Anything more than a simple function, you will most likely need a bunch of code to build the inputs and outputs. For most encodings, it is much easier to describe a function's main function than to write code to complete the test. Most of the time my test code line is several times the function implementation itself, but the document comments only need a few lines. In addition, the test simply explains the functions of the function. What is the function's design function? They do not explain why, but as mentioned earlier, design purposes and intentions are always more important. You really should test your code, and with some boundary test cases, testing is useful for judging whether code is working properly under boundary conditions. But in general, if you have to read the test case to understand the point of the code, then it is a dangerous signal, tell us to write more and better comments. # # Conclusion In addition to some very simple examples, the boundaries of useful annotations and useless annotations are very difficult to find. So, I'd rather people stand on the side of writing notes. You don't know who the next person who might be reading your code is, so helping them is to write a bunch of comments as much as you can. Try to write as much as you think, and then write more, and this number is just right.

via:https://npf.io/2017/11/comments/

Author: Nate Finch Translator: Arthurlee proofreading: Rxcai

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

1483 reads
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.