代码整洁之道——10、注释

一、只对复杂业务逻辑添加注释

注释是代码的解释说明,不是必须的,好的代码本身就是文档。

Bad:
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;
  }
}

Good:
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;
  }
}

二、不要把注释掉的代码放在代码库里

版本控制的原因就是把老代码放在历史库中。

Bad:
doStuff();
// doOtherStuff();
// doSomeMoreStuff();
// doSoMuchStuff();

Good:
doStuff();

三、不要有日志式的注释

记住,使用版本控制。不要有没用到的代码,注释掉的代码,尤其是日志式的注释。使用git log获取历史记录

Bad:
/**
 * 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;
}


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

四、避免占位符

它们通常是添加了干扰,用合适的缩进和格式化让函数、变量提供一种视觉结构。

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

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

Good:
$scope.model = {
  menu: 'foo',
  nav: 'bar'
};

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

 

posted on 2017-07-27 11:34  小小驰  阅读(200)  评论(0编辑  收藏  举报