为什么代码要整洁?
代码质量与整洁度成正比。有的团队在赶工期的时候,不注重代码的整洁,代码写的越来越糟糕,项目越来越混乱,生产力也跟着下降,那就必须找更多人来提高生产力,开发成本越来越高。
整洁的代码是怎样的?
清晰表达意图、消除重复、简单抽象、能通过测试。 换句话说:具有可读性、可重用性和可重构性。
- 名副其实:不使用缩写、不使用让人误解的名称,不要让人推测。
// bad: 啥?
const yyyymmdstr = moment().format("YYYY/MM/DD");
// bad: 缩写
const cD = moment().format("YYYY/MM/DD");
// good:
const currentDate = moment().format("YYYY/MM/DD");const locations = ["Austin", "New York", "San Francisco"];
// bad:推测l是locations的项
locations.forEach(l => doSomeThing(l));
// good
locations.forEach(location => doSomeThing(location));
- 使用方便搜索的名称:避免硬编码,对数据用常量const记录。
// bad: 86400000指的是?
setTimeout(goToWork, 86400000);
// good: 86400000是一天的毫秒数
const MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000;
setTimeout(goToWork, MILLISECONDS_PER_DAY);
- 类名应该是名词,方法名应该是动词。
// bad
function visble() {}
// good
function getVisble() {}
- 多个变量属于同一类型的属性,那就他们整合成一个对象。同时省略多余的上下文。
// bad:可以整合
const carMake = "Honda",
const carModel = "Accord",
const carColor = "Blue",
// bad: 多余上下文
const Car = {
carMake: "Honda",
carModel: "Accord",
carColor: "Blue",
};
// good
const Car = {
make: "Honda",
model: "Accord",
color: "Blue",
};
其他:
- 不要写多余的废话,比如
theMessage
的the
可以删除。 - 统一术语。比如通知一词,不要一会在叫
notice
,一会叫announce
。 - 用读得通顺的词语。比如
getElementById
就比useIdToGetElement
好读。
- 删除重复的代码,don’t repeat yourself。很多地方可以注意dry,比如偷懒复制了某段代码、try…catch或条件语句写了重复的逻辑。
// bad
try {
doSomeThing();
clearStack();
} catch (e) {
handleError(e);
clearStack();
}
// good
try {
doSomeThing();
} catch (e) {
handleError(e);
} finally {
clearStack();
}
- 形参不超过三个,对测试函数也方便。多了就使用对象参数。
- 同时建议使用对象解构语法,有几个好处:
- 能清楚看到函数签名有哪些熟悉,
- 可以直接重新命名,
- 解构自带克隆,防止副作用,
- Linter检查到函数未使用的属性。
// bad
function createMenu(title, body, buttonText, cancellable) {}
// good
function createMenu({ title, body, buttonText, cancellable }) {}
- 函数只做一件事,代码读起来更清晰,函数就能更好地组合、测试、重构。
// bad: 处理了输入框的change事件,并创建文件的切片,并保存相关信息到localStorage
function handleInputChange(e) {
const file = e.target.files[0];
// --- 切片 ---
const chunkList = [];
let cur = 0;
while (cur < file.size) {
chunkList.push({
chunk: file.slice(cur, cur + size)
});
cur += size;
}
// --- 保存信息到localstorage ---
localStorage.setItem("file", file.name);
localStorage.setItem("chunkListLength", chunkList.length);
}
// good: 将三件事分开写,同时自顶而下读,很舒适
function handleInputChange(e) {
const file = e.target.files[0];
const chunkList = createChunk(file);
saveFileInfoInLocalStorage(file, chunkList);
}
function createChunk(file, size = SLICE_SIZE) {
const chunkList = [];
let cur = 0;
while (cur < file.size) {
chunkList.push({
chunk: file.slice(cur, cur + size)
});
cur += size;
}
return chunkList
}
function saveFileInfoInLocalStorage(file, chunkList) {
localStorage.setItem("file", file.name);
localStorage.setItem("chunkListLength", chunkList.length);
}
- 自顶向下地书写函数,人们都是习惯自顶向下读代码,如,为了执行A,需要执行B,为了执行B,需要执行C。如果把A、B、C混在一个函数就很难读了。(看前一个的例子)。
- 不使用布尔值来作为参数,遇到这种情况时,一定可以拆分函数。
暂无评论内容