This is the 71st original article without water, if you want to get more original articles, please search the public account to follow us. This article was first published on the cloud blog: Writing high quality maintainable code: At a glance comments

preface

Some people believe that good code is self-explanatory. Proper naming and good code can make it easier for developers to read code, and code that is not particularly complex may indeed be self-explanatory. Not all scenarios can do this, so let’s take a look at comments.

A programming language interpretation of comments

Comments are explanations and instructions for code. A comment is an explanation or reminder given to a piece of code by a developer while writing a program, which helps improve the readability of the program code. Comments are not compiled by the computer.

Should I add a comment? Why add a comment?

Comments exist to facilitate second reading, code maintenance and project handover. A better understanding of the code helps improve collaboration and speed up the development process.

Imagine adding a piece of logically complex code and looking at it a few months later. Can you quickly understand it? You just took on an old project with almost no comments and complex logic. Can you read the code and understand the business efficiently?

Therefore, it is necessary to add comments.

Based on article

Shortcut keys Windows: CTRL +/ MAC: Command +/

Classification of annotations

Comments in HTML

<div>This is a line of text<! -- This is a line of annotated text -->
</div>
Copy the code

2. Comments in CSS

  • In the.html file
<style>
  div {
      /* color: #fff;  */
   }
</style>
Copy the code
  • In the.css file
div {
	/* color: #fff;  */
}
Copy the code
  • In.less or.scss files
div {
	/* color: #fff; * /  /* Multi-line comments */
	// font-size: 14px; // Single-line comment
	background: # 000;
}
Copy the code

Comments in JS

  • usage
    • Can be used to interpret JavaScript code and enhance its readability.
    • It can also be used to prevent code execution.
  • Single line comment (line comment) — to// At the beginning. Any in//All subsequent text will be commented out
// Define an empty array
var ary = [];
var ary2 = []; // Define an empty array
Copy the code
  • Multi-line comments (block comments) – to/ *At the beginning,* /At the end. Any in/ ** /The text between is annotated
/* This is a multi-line comment defining an array */
var ary = [];
Copy the code
  • Use comments to prevent code execution – annotated JS code will not be executed
//alert("123") // This message is not displayed during execution
alert("456")  // The message is displayed during execution
Copy the code
  • Function annotations
    • General with/ * *At the beginning,* /At the end. Any in/ * ** /The text between is annotated
/** ** submit **@method onSubmit
 * @param {[Object]} Submit data@return  {[Bollean]}  [Returns whether the submission was successful] */
const onSubmit = (params = {}) = > {
  const result = false;
    if (params) {
			result = true;
		}
	return result;
};
Copy the code

Special marking notes

  • **TODO ** There is functionality to be written in this comment, and the functionality to be implemented is outlined in the description
  • FIXME says at this comment that the code needs to be fixed, or even that the code is wrong, doesn’t work, and needs to be fixed. How to fix it is outlined in the description
  • **XXX ** In this note, although the code realizes the function, but the implementation method remains to be discussed, hope to improve in the future, the improvement will be briefly explained in the description
  • **NOTE ** How does the code work in this comment
  • **HACK ** is badly written or badly formatted in this comment and needs to adjust the program code to suit your needs
  • **BUG ** There is a BUG in this comment
// TODO is not complete
// FIXME to be fixed
// the implementation method of XXX needs to be confirmed
// NOTE
// HACK
// there is a BUG here
const arr = []
Copy the code

Tips:

  • why//Comments can be used in.less or.scss files, but not in.html or.css files.
    • inMDNComments on CSS are available only in/ * * /A grammar. However, the syntax for annotation support in LESS and SCSS remains the same as in JS, with single-line comments// And multi-line comments/ * * /Two kinds. Single-line comments are not retained after compilation.
  • Why are single-line comments sometimes written above and sometimes behind the code?
    • Comments can be written anywhere in the code. As far as I’m concerned, writing above code means a comment on the next line of code, while writing behind code means a comment on the line of code.

Specification of annotation writing

  • File comment
    • It is located in the header of the file and usually contains the summary, author, version change information, and modification time
  /* * Describe the current file function * @author author name * @version Version number last edited * @description Version change information */
Copy the code
  • Single-line comments
    • Always in//Leave a space behind
  // This is a line comment
Copy the code
  • Multiline comment
    • Always align the asterisk vertically (with a space before the terminator)
    • Do not comment on the beginning or end lines
    • Use single-line comments instead of multi-line comments whenever possible
    • Multi-line comments are recommended when commenting functions
  /* There's a comment here and a comment here and a comment here */
Copy the code
  • Function annotations
    • Each line in between begins with*First, and first with the first line*alignment
    • Note content and*Leave a space between them
    • Tag comments must be included. Ex. :
/** * method description *@method The method name *@for Owning class name *@param {parameter type} Parameter Description *@return {return value type} The return value is */
Copy the code

Annotate common tag usage

  • @type {typeName}
    • *Represents any type
    • ?Can be expressed asnull
    • !Cannot benull
    • []Said array
/ * * *@type {number}* /
var foo1;

/ * * *@type {*}
* @desc Any type */
var foo2;

/ * * *@type {? string}
* @desc String or NULL */
var foo3;

Copy the code
  • @param {} name – some description
    • Non-mandatory parameters must be added to the parameter name[]
    • This parameter is required if it has a default value=said
    • If the parameter is Object, continue to use it@paramDescribe its properties in detail
    • Several parameters are used.said
/ * * *@func
 * @desc A function with arguments *@param {string} a- Parameter A *@param {number} B =1 - Parameter b defaults to 1 *@param {string} C =1 - Parameter c has two supported values: 1 - x 2 - XX *@param {object} d- Parameter d is an object *@param {string} D.e - the e attribute * of parameter d@param {object[]} g- The argument g is an array of objects *@param {string} G.h - the h property * of an item in the parameter g array@param {string} [j] - Parameter j is an optional parameter */
 function foo(a, b, c, d, g, j) {}

/ * * *@func
 * @desc A function that takes several arguments *@param {... string} a- Parameter A */
function bar(a) {}
Copy the code

See JSDoc for more information

Expand the article

IE Conditional Comment (IE5+)

IE conditional comments are divided into the following situations:

  • Only IE interpretation is allowed<! --[if IE]><! [endif]-->
  • Only IE specific versions are allowed to explain execution<! --[if IE 7]><! [endif]-->
  • Only non-IE specific versions are allowed to perform comments<! --[if !IE 7]><! [endif]-->
  • Only comments above or below a particular version of IE are allowed to be executed<! --[if gt IE 7]><! [endif]-->
 <head>
  	<title>IE conditional comment</title>
  
  	<! -- Internet Explorer -->
    <! --[if IE]> <link href="style.css" rel="stylesheet" type="text/css" /> <! [endif]-->
  
    <! -- IE 7 -->
 	 	<! --[if IE 7]> <link href="style.css" rel="stylesheet" type="text/css" /> <! [endif]-->
 
    <!-- 不是 IE 7 时 -->
  	<! --[if !IE 7]> <link href="style.css" rel="stylesheet" type="text/css" /> <! [endif]-->
  
  	<! --> IE 7
  	<! --[if gt IE 7]> <link href="style.css" rel="stylesheet" type="text/css" /> <! [endif]-->
 
  	<! -- < IE 7 -->
   	<! --[if lt IE 7]> <link href="style.css" rel="stylesheet" type="text/css" /> <! [endif]-->
</head>
Copy the code

# (hash) comment and “” (triple quotes) comment

  • #Common in various script configuration files, used with JS single line comments//Pretty much the same. It’s also used a lot in Python
  • ' ' 'Multiline comment syntax in Python. Use two' ' 'Contains annotated paragraphs
# Python single-line comment 1
	print("I could have code like this.") # Python single-line comment 2

# print("This won't run."

Print ("This won't run.")"
Copy the code

Comment “executed”?

As we all know, commented code is not executed. A comment in Java was “executed”.

public class Test {
	public static void main(String[] args) {
		String name = "Zhao big";
		// \u000dname=" ";System.out.println(name); }}Copy the code

The result of this code execution is money two, that is, in this code, the “commented” line of code is in effect!

The problem with this code is the special character \u000d. \u000d is a string of Unicode characters representing newlines. The Java compiler not only compiles code, but also parses Unicode characters. The above code parses \u000d, and the following code goes to the following line, which is beyond the scope of the comment (single-line comment is only in the current line), so the result is money two instead of zauda. (below)

public class Test {
	public static void main(String[] args) {
		String name = "Zhao big";
		//
		name="Money"; System.out.println(name); }}Copy the code

So essentially the name=” money two “is not commented out when the code is executed, but replaced with a line (strange knowledge added). So remember, comments are not executed!

Annotation related plug-ins

Json file (open the Vscode file settings.json via ‘file – Preferences – Settings’).

  • KoroFileHeader is a plug-in used in vscode to generate file header comments and function comments
  • Add comments to the file header
    • Add comments at the beginning of the file to record file information/file input/output parameters, etc
    • Supports highly customized annotation options for various requirements and annotations.
    • When saving a file, the last edit time and editor are automatically updated
    • Shortcut:window:ctrl+alt+i.mac:ctrl+cmd+i.linux:ctrl+meta+i

  • Add a function comment at the cursor
    • Automatically generates a comment template at the cursor
    • Support for highly customized annotation options
    • Shortcut:window:ctrl+alt+t.mac:ctrl+cmd+t.linux:ctrl+meta+t
    • The shortcut keys are not available and are most likely occupied. See here
    • You can customize default parameters

  • Better CommentsImprove code annotation by annotating with alerts, messages, TODO, etc. Using this extension, you will be able to categorize comments into:
    • alerts
    • The query
    • todo
    • Emphasis on
    • Commented out code can also be styled so that the code should not exist
    • Additional annotation styles can be customized to specify

  • TODO HighlightHighlight TODO, FIXME, and any keywords
    • Highlight the built-in keywords to override the appearance with custom Settings
    • You can also customize keywords

Speak with the facts

Seeing is believing. Let’s take a look at the specifics of actual development:

  • There is no comment
const noWarehousetemIds = beSelectSkucontainer.reduce((arr, itemId) = > {
    const res = Object.keys(selectRowskey[itemId]).every((skuId) = > {
      const sku = selectRowskey[itemId][skuId];
      return!!!!! sku.warehouseCode || lodashGet(warehouses,'[0].code');
    });
    if(! res) { arr.push(itemId); }returnarr; } []);if (noWarehousetemIds.length > 0 || noStockItemIds.length > 0) {
    const itemIds = Array.from(new Set([...noWarehousetemIds, ...noStockItemIds]));
    const itemNames = itemIds.map(i= > this.itemNameMap[i].itemName);
    return Modal.warning({
      title: 'Error message'.content: `"${itemNames.join(', ')}"Inventory information is not perfect, please improve inventory information '}); }Copy the code
  • General comment
// Iterate over all skUs currently selected to find no itemids in stock
const noStockItemIds = beSelectSkucontainer.reduce((arr, itemId) = > {
  const res = Object.keys(selectRowskey[itemId]).every((skuId) = > {
    const sku = selectRowskey[itemId][skuId];
    return!!!!! sku.stockQuantity; });if(! res) { arr.push(itemId); }returnarr; } []);// Check if one SKU is empty
if (noStockItemIds.length > 0) {
  const itemNames = itemIds.map(i= > this.itemNameMap[i].itemName);
  return Modal.warning({
    title: 'Error message'.content: `"${itemNames.join(', ')}"Inventory information is not perfect, please improve inventory information '}); }Copy the code
  • Better comments
// Iterate over all skUs currently selected to find no itemids in stock
const noStockItemIds = beSelectSkucontainer.reduce((arr, itemId) = > {
    // selectRowskey is an object with itemId as its key, SKU as its value, SKU as its key, skU as its value, skU as its value, skU as its value, skU as its value, skU as its value, skU as its key, skU as its value, and skU as its value
    /* selectRowskey: {12345678: {// itemId 123456: {// skuId name: 'sku',}}} */
    const res = Object.keys(selectRowskey[itemId]).every((skuId) = > {
        const sku = selectRowskey[itemId][skuId];
        return!!!!! sku.stockQuantity; });// As long as one skU is out of stock, it is stuffed into the ARR and returned to the noStockItemIds array
    if(! res) { arr.push(itemId); }returnarr; } []);// Check if one SKU is empty
if (noStockItemIds.length > 0) {
    // Find the product name by id
    const itemNames = itemIds.map(i= > this.itemNameMap[i].itemName);
    Modal.warning({
        title: 'Error message'.content: `"${itemNames.join(', ')}"Inventory information is not perfect, please improve inventory information '}); }Copy the code

Looking at the above code, it is obvious that there are no comments and the importance of writing comments clearly. If you write a comment but still can’t understand it, you might as well not write it.

Comments don’t just have to be written. They describe what a piece of code does, explain the logic, and allow the developer to “mindlessly” browse through it.

I saw someone post this picture in the workgroup, which I think is a good example of code comment:

conclusion

Now, you have your own idea of the importance of comments. There are a few other things to keep in mind when writing comments:

  • Keep your comments concise and clear. You don’t need to add comments to every line of code

  • If the code changes, remember to modify the corresponding comment. Do not have comments that are out of date, or they will be counterproductive

    Feel free to leave your comments in the comments section below

reference

Why write comments Js /javascript Code Comments Specification and Special comments in sample code — TODO, FIXME, XXX What comments do, and how to write comments Are you sure Java comments won’t be executed? 80% of people don’t know. Internet Explorer Conditional comment Details about the Internet Explorer conditional comment in the CSS

Recommended reading

My path to career advancement

XSS attacks in React

, recruiting

ZooTeam, a young passionate and creative front-end team, belongs to the PRODUCT R&D department of ZooTeam, based in picturesque Hangzhou. The team now has more than 40 front-end partners, with an average age of 27, and nearly 30% of them are full-stack engineers, no problem in the youth storm group. The members consist of “old” soldiers from Alibaba and netease, as well as fresh graduates from Zhejiang University, University of Science and Technology of China, Hangzhou Electric And other universities. In addition to daily business docking, the team also carried out technical exploration and practice in material system, engineering platform, building platform, performance experience, cloud application, data analysis and visualization, promoted and implemented a series of internal technical products, and continued to explore the new boundary of front-end technology system.

If you want to change what’s been bothering you, you want to start bothering you. If you want to change, you’ve been told you need more ideas, but you don’t have a solution. If you want change, you have the power to make it happen, but you don’t need it. If you want to change what you want to accomplish, you need a team to support you, but you don’t have the position to lead people. If you want to change the pace, it will be “5 years and 3 years of experience”; If you want to change the original savvy is good, but there is always a layer of fuzzy window… If you believe in the power of believing, believing that ordinary people can achieve extraordinary things, believing that you can meet a better version of yourself. If you want to be a part of the process of growing a front end team with deep business understanding, sound technology systems, technology value creation, and impact spillover as your business takes off, I think we should talk. Any time, waiting for you to write something and send it to [email protected]