浅谈JavaScript 代码简洁之道(13)
Good:
class PerformanceReview {
constructor(employee) {
this.employee = employee;
}
perfReview() {
this.getPeerReviews();
this.getManagerReview();
this.getSelfReview();
}
getPeerReviews() {
const peers = this.lookupPeers();
// ...
}
lookupPeers() {
return db.lookup(this.employee, 'peers');
}
getManagerReview() {
const manager = this.lookupManager();
}
lookupManager() {
return db.lookup(this.employee, 'manager');
}
getSelfReview() {
// ...
}
}
const review = new PerformanceReview(employee);
review.perfReview();
注释
只有业务逻辑需要注释
代码注释不是越多越好。
Bad:
function hashIt(data) {
// 这是初始值
let hash = 0;
// 数组的长度
const length = data.length;
// 循环数组
for (let i = 0; i < length; i++) {
// 获取字符代码
const char = data.charCodeAt(i);
// 修改 hash
hash = ((hash << 5) - hash) + char;
// 转换为32位整数
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;
// 转换为32位整数
hash &= hash;
}
}
删掉注释的代码
git 存在的意义就是保存你的旧代码,所以注释的代码赶紧删掉吧。
Bad:
doStuff(); // doOtherStuff(); // doSomeMoreStuff(); // doSoMuchStuff();
Good:
doStuff();
不要记日记
记住你有 git!,git log 可以帮你干这事。
Bad:
/**
* 2016-12-20: 删除了 xxx
* 2016-10-01: 改进了 xxx
* 2016-02-03: 删除了第12行的类型检查
* 2015-03-14: 增加了一个合并的方法
*/
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() {
// ...
};
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:http://www.heiqu.com/90.html
