Skip to content

注释规范

仅对涉及业务逻辑复杂性的代码添加注释

注释是补救措施而非强制要求。良好的代码大多能够自我说明

反面示例:

javascript
function hashIt(data) {
  // The hash
  let hash = 0;

  // Length of string
  const length = data.length;

  // Loop through every character in data
  for (let i = 0; i < length; i++) {
    // Get character code.
    const char = data.charCodeAt(i);
    // Make the hash
    hash = (hash << 5) - hash + char;
    // Convert to 32-bit integer
    hash &= hash;
  }
}

正面示例:

javascript
function hashIt(data) {
  let hash = 0;
  const length = data.length;

  for (let i = 0; i < length; i++) {
    const char = data.charCodeAt(i);
    hash = (hash << 5) - hash + char;

    // Convert to 32-bit integer
    hash &= hash;
  }
}

不要在代码库中保留注释掉的代码

旧代码应保留在版本历史中,而非留在注释里

反面示例:

javascript
doStuff();
// doOtherStuff();
// doSomeMoreStuff();
// doSoMuchStuff();

正面示例:

javascript
doStuff();

避免使用日志式注释

记得使用版本控制!无需保留僵尸代码、注释代码,尤其是日志式注释。使用git log来获取历史记录

反面示例:

javascript
/**
 * 2016-12-20: Removed monads, didn't understand them (RM)
 * 2016-10-01: Improved using special monads (JP)
 * 2016-02-03: Removed type-checking (LI)
 * 2015-03-14: Added combine with type-checking (JR)
 */
function combine(a, b) {
  return a + b;
}

正面示例:

javascript
function combine(a, b) {
  return a + b;
}

避免使用位置标记

它们通常只是增加了噪音。让函数和变量名称以及恰当的缩进和格式化为代码提供视觉结构

反面示例:

javascript
////////////////////////////////////////////////////////////////////////////////
// Scope Model Instantiation
////////////////////////////////////////////////////////////////////////////////
$scope.model = {
  menu: "foo",
  nav: "bar"
};

////////////////////////////////////////////////////////////////////////////////
// Action setup
////////////////////////////////////////////////////////////////////////////////
const actions = function() {
  // ...
};

正面示例:

javascript
$scope.model = {
  menu: "foo",
  nav: "bar"
};

const actions = function() {
  // ...
};