浅谈JavaScript 代码整洁之道(16)

Comments

只注释业务逻辑复杂的内容

注释是用来解释代码的,而不是必须的。好的代码应该 自注释。

不好:

function hashIt(data) {
 // Hash 码
 var hash = 0;

 // 字符串长度
 var length = data.length;

 // 遍历数据中所有字符
 for (var i = 0; i < length; i++) {
  // 获取字符编码
  var char = data.charCodeAt(i);
  // 生成 Hash
  hash = ((hash << 5) - hash) + char;
  // 转换为32位整数
  hash = hash & hash;
 }
}

好:

function hashIt(data) {
 var hash = 0;
 var length = data.length;

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

  // 转换为32位整数
  hash = hash & hash;
 }
}

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

版本控制存在的原因就是保存你的历史代码。

不好:

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

好:

doStuff();

不需要日志式的注释

记住,使用版本控制!没用的代码、注释掉的代码,尤其是日志式的注释。用 git log 来获取历史信息!

不好:

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

好:

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

避免位置标记

位置标记通常只会添加垃圾信息。通过对函数或变量名以及适当的缩进就能为代码带来良好的可视化结构。

不好:

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

////////////////////////////////////////////////////////////////////////////////
// Action setup
////////////////////////////////////////////////////////////////////////////////
let actions = function() {
 // ...
}

好:

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

let actions = function() {
 // ...
}

避免在源文件中添加版权注释

这是代码文件树顶层的 LICENSE 文件应该干的事情。

不好:

/*
The MIT License (MIT)

Copyright (c) 2016 Ryan McDermott

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
*/

function calculateBill() {
 // ...
}


      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/417.html