26個(gè)寫出簡(jiǎn)潔優(yōu)雅JavaScript代碼的技巧
寫在前面
在編程世界中,代碼不僅僅是讓事情正常運(yùn)轉(zhuǎn)。 它就像一件講述故事的藝術(shù)品。 當(dāng)代碼干凈時(shí),它就像一個(gè)美麗的、精心制作的雕塑,既美觀又運(yùn)行良好。
但在急于按期完成任務(wù)的過程中,有時(shí)團(tuán)隊(duì)不會(huì)太注意保持代碼的整潔。 這可能會(huì)導(dǎo)致項(xiàng)目變得混亂、復(fù)雜,變得更加難以開展。 隨著情況變得更糟,生產(chǎn)力也會(huì)下降。 然后,公司需要引進(jìn)更多的人來提供幫助,這使得一切都變得更加昂貴。
那么,干凈的代碼是什么樣的呢? 它的代碼易于理解,沒有多余的部分,簡(jiǎn)單,并且可以通過測(cè)試。 換句話說,它是可讀的、可重用的,并且在需要時(shí)易于更改。
為了幫助你編寫出色的 JavaScript 代碼,我將在今天的內(nèi)容中與你分享 26 個(gè)寫干凈代碼的技巧,這些技巧將指導(dǎo)你編寫既優(yōu)雅又高效的代碼。
一、變量
1.使用有意義且易于發(fā)音的變量名
// Bad
const yyyymmdstr = moment().format("YYYY/MM/DD");
// Good
const currentDate = moment().format("YYYY/MM/DD");
2. 同一類型的變量使用相同的詞匯表
// Bad
getUserInfo();
getClientData();
getCustomerRecord();
// Good
getUser();
3. 使用可搜索的名稱
我們將閱讀比我們編寫的更多的代碼,我們編寫的代碼可讀且可搜索,這一點(diǎn)很重要。
// Bad
// What the heck is 86400000 for?
setTimeout(blastOff, 86400000);
// Good
// Declare them as capitalized named constants.
const MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000; //86400000;
setTimeout(blastOff, MILLISECONDS_PER_DAY);
4. 使用解釋變量
// Bad
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(
address.match(cityZipCodeRegex)[1],
address.match(cityZipCodeRegex)[2]
);
// Good
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
const [_, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);
5. 避免心理映射
顯式的比隱式的好。
// Bad
const locations = ["Austin", "New York", "San Francisco"];
locations.forEach(l => {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
// Wait, what is `l` for again?
dispatch(l);
});
// Good
const locations = ["Austin", "New York", "San Francisco"];
locations.forEach(location => {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
dispatch(location);
});
6. 不要添加不需要的上下文
如果您的類/對(duì)象名稱告訴您一些信息,請(qǐng)不要在變量名稱中重復(fù)該信息。
// Bad
const Car = {
carMake: "Honda",
carModel: "Accord",
carColor: "Blue"
};
function paintCar(car, color) {
car.carColor = color;
}
// Good
const Car = {
make: "Honda",
model: "Accord",
color: "Blue"
};
function paintCar(car, color) {
car.color = color;
}
7. 使用默認(rèn)參數(shù)代替短路或條件
默認(rèn)參數(shù)通常比短路更清晰。 請(qǐng)注意,如果您使用它們,您的函數(shù)將只為未定義的參數(shù)提供默認(rèn)值。 其他“假”值(例如 ''、""、false、null、0 和 NaN)不會(huì)被默認(rèn)值替換。
// Bad
function createMicrobrewery(name) {
const breweryName = name || "Hipster Brew Co.";
// ...
}
// Good
function createMicrobrewery(name = "Hipster Brew Co.") {
// ...
}
二、功能
8. 函數(shù)參數(shù)(理想情況下為 2 個(gè)或更少)
限制函數(shù)參數(shù)的數(shù)量非常重要,因?yàn)樗箿y(cè)試函數(shù)變得更加容易。 超過三個(gè)會(huì)導(dǎo)致組合爆炸,您必須使用每個(gè)單獨(dú)的參數(shù)來測(cè)試大量不同的情況。
// Bad
function createMenu(title, body, buttonText, cancellable) {
// ...
}
createMenu("Foo", "Bar", "Baz", true);
//Good
function createMenu({ title, body, buttonText, cancellable }) {
// ...
}
createMenu({
title: "Foo",
body: "Bar",
buttonText: "Baz",
cancellable: true
});
9.函數(shù)應(yīng)該做一件事
這是迄今為止軟件工程中最重要的規(guī)則。 當(dāng)函數(shù)做不止一件事時(shí),它們就更難編寫、測(cè)試和推理。 當(dāng)您可以將一個(gè)函數(shù)隔離為一個(gè)操作時(shí),就可以輕松重構(gòu)它,并且您的代碼讀起來會(huì)更清晰。 如果您除了本指南之外沒有任何其他內(nèi)容,您將領(lǐng)先于許多開發(fā)人員。
// Bad
function emailClients(clients) {
clients.forEach(client => {
const clientRecord = database.lookup(client);
if (clientRecord.isActive()) {
email(client);
}
});
}
// Good
function emailActiveClients(clients) {
clients.filter(isActiveClient).forEach(email);
}
function isActiveClient(client) {
const clientRecord = database.lookup(client);
return clientRecord.isActive();
}
10.函數(shù)名稱應(yīng)該說明它們的作用
// Bad
function addToDate(date, month) {
// ...
}
const date = new Date();
// It's hard to tell from the function name what is added
addToDate(date, 1);
// Good
function addMonthToDate(month, date) {
// ...
}
const date = new Date();
addMonthToDate(1, date);
11.函數(shù)應(yīng)該只是一層抽象
當(dāng)你有多個(gè)抽象級(jí)別時(shí),你的函數(shù)通常會(huì)做太多事情。 拆分功能可以實(shí)現(xiàn)可重用性和更容易的測(cè)試。
// Bad
function parseBetterJSAlternative(code) {
const REGEXES = [
// ...
];
const statements = code.split(" ");
const tokens = [];
REGEXES.forEach(REGEX => {
statements.forEach(statement => {
// ...
});
});
const ast = [];
tokens.forEach(token => {
// lex...
});
ast.forEach(node => {
// parse...
});
}
// Good
function parseBetterJSAlternative(code) {
const tokens = tokenize(code);
const syntaxTree = parse(tokens);
syntaxTree.forEach(node => {
// parse...
});
}
function tokenize(code) {
const REGEXES = [
// ...
];
const statements = code.split(" ");
const tokens = [];
REGEXES.forEach(REGEX => {
statements.forEach(statement => {
tokens.push(/* ... */);
});
});
return tokens;
}
function parse(tokens) {
const syntaxTree = [];
tokens.forEach(token => {
syntaxTree.push(/* ... */);
});
return syntaxTree;
}
12. 刪除重復(fù)代碼
盡最大努力避免重復(fù)代碼。 重復(fù)的代碼是不好的,因?yàn)檫@意味著如果您需要更改某些邏輯,則需要在多個(gè)地方進(jìn)行更改。
// Bad
function showDeveloperList(developers) {
developers.forEach(developer => {
const expectedSalary = developer.calculateExpectedSalary();
const experience = developer.getExperience();
const githubLink = developer.getGithubLink();
const data = {
expectedSalary,
experience,
githubLink
};
render(data);
});
}
function showManagerList(managers) {
managers.forEach(manager => {
const expectedSalary = manager.calculateExpectedSalary();
const experience = manager.getExperience();
const portfolio = manager.getMBAProjects();
const data = {
expectedSalary,
experience,
portfolio
};
render(data);
});
}
// Good
function showEmployeeList(employees) {
employees.forEach(employee => {
const expectedSalary = employee.calculateExpectedSalary();
const experience = employee.getExperience();
const data = {
expectedSalary,
experience
};
switch (employee.type) {
case "manager":
data.portfolio = employee.getMBAProjects();
break;
case "developer":
data.githubLink = employee.getGithubLink();
break;
}
render(data);
});
}
13. 使用Object.assign設(shè)置默認(rèn)對(duì)象
// Bad
const menuConfig = {
title: null,
body: "Bar",
buttonText: null,
cancellable: true
};
function createMenu(config) {
config.title = config.title || "Foo";
config.body = config.body || "Bar";
config.buttonText = config.buttonText || "Baz";
config.cancellable =
config.cancellable !== undefined ? config.cancellable : true;
}
createMenu(menuConfig);
// Good
const menuConfig = {
title: "Order",
// User did not include 'body' key
buttonText: "Send",
cancellable: true
};
function createMenu(config) {
let finalConfig = Object.assign(
{
title: "Foo",
body: "Bar",
buttonText: "Baz",
cancellable: true
},
config
);
return finalConfig
// config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}
// ...
}
createMenu(menuConfig);
14. 不要使用標(biāo)志作為函數(shù)參數(shù)
標(biāo)志告訴你的用戶這個(gè)函數(shù)不止做一件事。 函數(shù)應(yīng)該做一件事。 如果函數(shù)遵循基于布爾值的不同代碼路徑,則拆分它們。
// Bad
function createFile(name, temp) {
if (temp) {
fs.create(`./temp/${name}`);
} else {
fs.create(name);
}
}
// Good
function createFile(name) {
fs.create(name);
}
function createTempFile(name) {
createFile(`./temp/${name}`);
}
15.不要寫入全局函數(shù)
在 JavaScript 中污染全局變量是一種不好的做法,因?yàn)槟憧赡軙?huì)與另一個(gè)庫(kù)發(fā)生沖突,并且 API 的用戶在生產(chǎn)中遇到異常之前不會(huì)意識(shí)到這一點(diǎn)。
// Bad
Array.prototype.diff = function diff(comparisonArray) {
const hash = new Set(comparisonArray);
return this.filter(elem => !hash.has(elem));
};
// Good
class SuperArray extends Array {
diff(comparisonArray) {
const hash = new Set(comparisonArray);
return this.filter(elem => !hash.has(elem));
}
}
16. 優(yōu)先使用函數(shù)式編程而不是命令式編程
JavaScript 不像 Haskell 那樣是一種函數(shù)式語言,但它具有函數(shù)式風(fēng)格。 函數(shù)式語言可以更簡(jiǎn)潔、更容易測(cè)試。 盡可能喜歡這種編程風(fēng)格。
// Bad
const programmerOutput = [
{
name: "Uncle Bobby",
linesOfCode: 500
},
{
name: "Suzie Q",
linesOfCode: 1500
},
{
name: "Jimmy Gosling",
linesOfCode: 150
},
{
name: "Gracie Hopper",
linesOfCode: 1000
}
];
let totalOutput = 0;
for (let i = 0; i < programmerOutput.length; i++) {
totalOutput += programmerOutput[i].linesOfCode;
}
// Good
const programmerOutput = [
{
name: "Uncle Bobby",
linesOfCode: 500
},
{
name: "Suzie Q",
linesOfCode: 1500
},
{
name: "Jimmy Gosling",
linesOfCode: 150
},
{
name: "Gracie Hopper",
linesOfCode: 1000
}
];
const totalOutput = programmerOutput.reduce(
(totalLines, output) => totalLines + output.linesOfCode,
0
);
17.封裝條件語句
// Bad
if (fsm.state === "fetching" && isEmpty(listNode)) {
// ...
}
// Good
function shouldShowSpinner(fsm, listNode) {
return fsm.state === "fetching" && isEmpty(listNode);
}
if (shouldShowSpinner(fsmInstance, listNodeInstance)) {
// ...
}
18.避免否定條件
// Bad
function isDOMNodeNotPresent(node) {
// ...
}
if (!isDOMNodeNotPresent(node)) {
// ...
}
// Good
function isDOMNodePresent(node) {
// ...
}
if (isDOMNodePresent(node)) {
// ...
}
三、并發(fā)性
19.使用 Promise,而不是回調(diào)
回調(diào)不干凈,并且會(huì)導(dǎo)致過多的嵌套。 在 ES2015/ES6 中,Promise 是內(nèi)置的全局類型。 使用它們!
// Bad
import { get } from "request";
import { writeFile } from "fs";
get(
"https://en.wikipedia.org/wiki/Robert_Cecil_Martin",
(requestErr, response, body) => {
if (requestErr) {
console.error(requestErr);
} else {
writeFile("article.html", body, writeErr => {
if (writeErr) {
console.error(writeErr);
} else {
console.log("File written");
}
});
}
}
);
// Good
import { get } from "request-promise";
import { writeFile } from "fs-extra";
get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin")
.then(body => {
return writeFile("article.html", body);
})
.then(() => {
console.log("File written");
})
.catch(err => {
console.error(err);
});
20. Async/Await 比 Promise 更簡(jiǎn)潔
Promise 是回調(diào)的一個(gè)非常干凈的替代方案,但 ES2017/ES8 帶來了 async 和 wait,它提供了更干凈的解決方案。
您所需要的只是一個(gè)以 async 關(guān)鍵字為前綴的函數(shù),然后您可以命令式地編寫邏輯,而無需 then 函數(shù)鏈。
// Bad
import { get } from "request-promise";
import { writeFile } from "fs-extra";
get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin")
.then(body => {
return writeFile("article.html", body);
})
.then(() => {
console.log("File written");
})
.catch(err => {
console.error(err);
});
// Good
import { get } from "request-promise";
import { writeFile } from "fs-extra";
async function getCleanCodeArticle() {
try {
const body = await get(
"https://en.wikipedia.org/wiki/Robert_Cecil_Martin"
);
await writeFile("article.html", body);
console.log("File written");
} catch (err) {
console.error(err);
}
}
getCleanCodeArticle()
四、錯(cuò)誤處理
拋出錯(cuò)誤是一件好事! 它們意味著運(yùn)行時(shí)已成功識(shí)別出程序中的某些問題,并且它會(huì)通過停止當(dāng)前堆棧上的函數(shù)執(zhí)行、終止進(jìn)程(在 Node 中)并通過堆棧跟蹤在控制臺(tái)中通知您來通知您。
21. 不要忽略捕獲的錯(cuò)誤
對(duì)捕獲的錯(cuò)誤不采取任何措施并不能讓您有能力修復(fù)或?qū)λ鲥e(cuò)誤做出反應(yīng)。 將錯(cuò)誤記錄到控制臺(tái) (console.log) 也好不了多少,因?yàn)樗3?huì)迷失在打印到控制臺(tái)的大量?jī)?nèi)容中。
如果您將任何代碼包裝在 try/catch 中,則意味著您認(rèn)為那里可能會(huì)發(fā)生錯(cuò)誤,因此您應(yīng)該為錯(cuò)誤發(fā)生時(shí)制定計(jì)劃或創(chuàng)建代碼路徑。
// Bad
try {
functionThatMightThrow();
} catch (error) {
console.log(error);
}
// Good
try {
functionThatMightThrow();
} catch (error) {
// One option (more noisy than console.log):
console.error(error);
// Another option:
notifyUserOfError(error);
// Another option:
reportErrorToService(error);
// OR do all three!
}
22. 不要忽視被拒絕的承諾
出于同樣的原因,您不應(yīng)該忽略 try/catch 中捕獲的錯(cuò)誤。
// Bad
getdata()
.then(data => {
functionThatMightThrow(data);
})
.catch(error => {
console.log(error);
});
// Good
getdata()
.then(data => {
functionThatMightThrow(data);
})
.catch(error => {
// One option (more noisy than console.log):
console.error(error);
// Another option:
notifyUserOfError(error);
// Another option:
reportErrorToService(error);
// OR do all three!
});
五、評(píng)論
23. 只評(píng)論具有業(yè)務(wù)邏輯復(fù)雜性的事物
評(píng)論是道歉,而不是要求。 好的代碼主要是文檔本身。
// 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;
}
}
24. 不要在代碼庫(kù)中留下注釋掉的代碼
版本控制的存在是有原因的。 將舊代碼留在您的歷史記錄中。
// Bad
doStuff();
// doOtherStuff();
// doSomeMoreStuff();
// doSoMuchStuff();
// Good
doStuff();
25.沒有期刊評(píng)論
請(qǐng)記住,使用版本控制! 不需要死代碼、注釋代碼,尤其是期刊注釋。 使用 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;
}
26. 避免位置標(biāo)記
它們通常只是增加噪音。 讓函數(shù)和變量名稱以及正確的縮進(jìn)和格式為代碼提供視覺結(jié)構(gòu)。
// 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() {
// ...
};
結(jié)論
從一開始就讓代碼干凈并不總是那么容易。 重要的是要記住,沒有必要執(zhí)著于使每條線路都完美,尤其是當(dāng)您的日程安排很緊時(shí)。 只是沒有足夠的時(shí)間來一遍又一遍地重寫代碼。
相反,專注于在有限的時(shí)間內(nèi)編寫最好的代碼。 當(dāng)下一輪更新到來并且您注意到可以改進(jìn)的內(nèi)容時(shí),這是進(jìn)行這些更改的好時(shí)機(jī)。
每個(gè)公司和每個(gè)項(xiàng)目都有自己的編碼風(fēng)格,它可能與我分享的技巧不同。 如果您加入一個(gè)已經(jīng)啟動(dòng)并運(yùn)行的項(xiàng)目,通常最好堅(jiān)持使用已經(jīng)存在的編碼風(fēng)格(除非您要重構(gòu)它)。 這是因?yàn)樵谡麄€(gè)代碼中保持一致的風(fēng)格也是保持代碼整潔的一種形式。
請(qǐng)記住,干凈的代碼是一個(gè)旅程,而不是目的地。 這是關(guān)于隨著時(shí)間的推移做出小的改進(jìn),而不是陷入完美。 通過應(yīng)用您所學(xué)到的技巧,您將能夠編寫出更簡(jiǎn)潔、更高效的 JavaScript 代碼,未來的您和其他人都會(huì)感謝您。
最后,感謝您的閱讀,也期待你的關(guān)注,祝編程快樂!