“Comment or not Comment, that is the question

Good comments improve code quality by making it more readable and maintainable.

So what is a good comment? How to write good comments? This article will discuss JS annotation from the purpose and principle of annotation.

01 Purpose and principles of annotations

Purpose of comments:

  • Improve the readability of your code, thereby increasing the maintainability of your code

Principles of annotation:

  • As short As possible

  • Be As detailed As necessary.

We write comments to help readers of the code (including ourselves, and possibly machines like JSDoc) read and understand the code and maintain it.


“Do not add comments unless necessary.”Is refers to the notes to avoid too much excessive, not for the sake of notes and notes. Redundant comments are equivalent to redundant code, and in addition to contributing to readability, changing comments can be a burden if the code needs to be changed.

We should go for “self-commenting code”, where the code itself is highly readable (through clear naming, reasonable structure, etc.). Here’s an example:

// bad // Render the table if the data is readyif (data.success && data.result.length > 0) {
  renderTable(data);  
}

// good
const isTableDataReady = data.success && data.result.length > 0;
if (isTableDataReady) {
  renderTable(data);
}Copy the code

“As detailed as necessary” means that comments should be as detailed as possible so that the reader can fully understand the logic and intent of the code.

02 What is a Good comment and what is a bad comment

According to the principles of comments, we should judge whether a comment is “necessary” based on whether it helps the reader read and understand the code better.

Good comments include:

  • To help readers better understand the code logic and structure, for example:

init: functionConst config = getConfig(); Const userInfo = getUserInfo(); // Perform initialization based on the configuration and user informationdoInit(config, userInfo); // If there is special logic for custom configurationif(config.custom) { ... }}Copy the code
  • An explanation of a particular or difficult way of writing, as:

/** 
 * parseInt was the reason my code was slow. 
 * Bitshifting the String to coerce it to a 
 * Number made it a lot faster. 
 */
const val = inputValue >> 0;
Copy the code
  • Special tag comments: tags that have special meanings, such as TODO, FIXME, etc

  • Notes on files: Some protocols stipulate that a fixed format of notes, such as author and agreement, should be written at the head of the file

  • Document-like comments: Some conventions stipulate that apis, classes, functions, etc., use document-like comments (jSDoc style)

  • Follow common style rules, such as certain Spaces and blank lines, to ensure the readability of comments themselves


Bad comments include:

  • Comments are unhelpful for reading code: as in the first example of this article, you could have self-commented your code without comments and with clear naming and logic

  • Does not follow uniform style rules such as single-line comment length, Spaces, blank lines, for example:

// Bad single-line comment is too long to read, // parseInt was the reason my code was slow. Bitbehavior the String to coerce it to Number made it a lot faster. const val = inputValue >> 0; // good /** * parseInt was the reason my code was slow. * Bitshifting the String to coerce it to a * Number made it a lot faster. */ const val = inputValue >> 0;Copy the code
  • Emotional comments: such as complaining, discrimination, funny, etc. (be found you kneel)





03 How to Write a good comment

Annotation specifications

Understand the purpose and principles of annotations and develop and follow a annotation protocol to ensure the readability and consistency of annotations

Tool to ensure

Examples include using ESLint to ensure a consistent comment style and Sonar to check project comment rates

04 Note Specification

Here is an annotated protocol for your reference (refer to the Airbnb protocol) :

4.1 [Recommended] Use // for single-line comments

Comments should be written on a single line above the commented object and not appended to a statement:

// bad
const active = true; // is current tab

// good
// is current tab
const active = true;Copy the code

A blank line is required above the comment line (unless the comment line is above the top of a block) to increase readability:

// bad
function getType() {  
  console.log('fetching type... ');  
  // set the default type to 'no type'
  const type = this.type || 'no type';  
  return type;
}
  
// good
function getType() {  
  console.log('fetching type... ');  
  
  // set the default type to 'no type'
  const type = this.type || 'no type';  
  return type; } // good // Comment lines above the top of a block do not need a blank linefunction getType() {  
  // set the default type to 'no type'
  const type = this.type || 'no type';					
  return type;
}Copy the code

4.2 [Recommended] Multi-line comments using /**… */ instead of multiple lines //

// bad
// make() returns a new element
// based on the passed in tag name
function make(tag) {
  // ...

  return element;
}

// good
/**
 * make() returns a new element
 * based on the passed-in tag name
 */
function make(tag) {
  // ...

  return element;
}Copy the code

4.3 [Mandatory] There must be a space between the comment content and the comment character to improve the readability. eslint: spaced-comment

// bad
//is current tab
const active = true;

// good
// is current tab
const active = true;

// bad
/**
 *make() returns a new element
 *based on the passed-in tag name
 */
function make(tag) {  
  // ...

  return element;
}

// good
/**
 * make() returns a new element
 * based on the passed-in tag name
 */
function make(tag) {  
  // ...

  return element;
}Copy the code

4.4 [Recommendation] Use special Comments

Sometimes we find a possible bug, but for some reason we can’t fix it. Or there may be some unfinished functionality somewhere, in which case we need to use corresponding special markup comments to inform future partners or ourselves. There are two kinds of special tags commonly used:

  • // FIXME: What is the explanatory problem

  • // TODO: describe what else TODO or the solution to the problem

class Calculator extends Abacus {
  constructor() { super(); // FIXME: shouldn't use a global here total = 0; // TODO: total should be configurable by an options param this.total = 0; }}Copy the code

4.5 document annotations, such as functions, classes, files, and events, should use jSDOC specifications

Such as:

Constructor * @constructor * @param {string} author - the author of the Book. */functionBook(title, author) { this.title=title; this.author=author; } the Book. The prototype = {/ * * * to obtain the title of the Book * @ returns {string} | * * / getTitle:function() {returnthis.title; }, /** * set the number of pages in the book * @param pageNum {number} page */setPageNum:function(pageNum){ this.pageNum=pageNum; }};Copy the code

05 tools

There are tools available to ensure annotation quality, such as:

Eslint: Ensures a consistent comment style

ESLint is one of the most popular javascript code checking tools. ESLint has several comment rules that you can optionally enable:

  • valid-jsdoc

  • require-jsdoc

  • no-warning-comments

  • capitalized-comments

  • line-comment-position

  • lines-around-comment

  • multiline-comment-style

  • no-inline-comments

  • spaced-comment

Sonar: Check the annotation rate of the project

Sonar is a code continuous integration platform that can statically scan code to get comment rate data for projects.

The comment rate reflects the proportion of comment lines in the total code line. Low comment rate is not good, but we should not blindly pursue high comment rate.

Also, like Eslint, Sonar has some rules for annotation style that can be configured.

06 afterword.

Understanding the purpose and principles of annotations, following a annotation protocol, and incorporating tools to ensure implementation can make annotations a good addition to your code, enhancing readability and maintainability, and thus improving code quality.

This is the first of a series of front-end code quality articles that will cover topics such as coding specifications, complexity, and repetition rates


Reference for some of the content and code examples in this article:

  • Aralejs annotation specifications https://github.com/aralejs/aralejs.github.io/wiki/JavaScript- comments

  • An encoding code https://github.com/airbnb/javascript#comments

  • http://zh-google-styleguide.readthedocs.io/en/latest/google-cpp-styleguide/comments/

Part of the distribution map from the network, if there is any intrusion, please contact the author




Follow the wechat official account for more original content