概述
我們之道作為一個(gè)碼農(nóng)搂鲫,不論其實(shí)現(xiàn)如何,功能怎樣磺平,寫的一手清晰靠譜的代碼是其代碼功力的體現(xiàn)魂仍。好的、清潔的代碼可以方便自己以后維護(hù)拣挪,讓你的繼任者馬上能接手維護(hù)它擦酌,而不是給你檫屁股,被人戳脊梁骨媒吗、被罵垃圾代碼仑氛。所以,寫清潔地代碼非常重要。
那么什么才是清潔代碼的呢锯岖?不言而喻介袜,清潔的代碼就是可以讓人易于人理解、易于更改出吹、方便擴(kuò)展的代碼遇伞。寫清潔的代碼要常捫心自問:
為什么要這樣寫?
為什么要在這兒寫捶牢?
為什么不換個(gè)寫法鸠珠?
Robert C. Martin在《代碼整潔之道》一書中說過:
就算是的壞代碼也能運(yùn)行,但如果代碼不干凈秋麸,也能會(huì)讓你的開發(fā)團(tuán)隊(duì)陷入困境渐排。
在本文中,蟲蟲就給大家講講JavaScript代碼的整潔知道灸蟆,全面對(duì)比下好的代碼和壞的代碼的寫法驯耻。
強(qiáng)類型檢查,使用"==="炒考,不用"=="
類型的檢查非常重要可缚,使用強(qiáng)類型檢查可以幫我理清程序邏輯,如果類型檢查松懈了(使用==)斋枢,有可能使你的邏輯"南轅北撤了"帘靡,試看下面的例子:
所以從現(xiàn)在開始就強(qiáng)類型檢查,"亡羊補(bǔ)牢瓤帚,猶未晚也"描姚!
const value = "520";
if (value === 520) {
console.log(value);
}
//條件不會(huì)滿足。
if (value === "520") {
console.log(value);
}
//條件滿足缘滥。
變量命名
變量的命名要有意義轰胁,而不是隨意亂起。最好是"望文生義"朝扼,一看到變量名就知道是干嘛用的赃阀。
望文生義
壞代碼:
let daysSLV= 10;
let y = new Date().getFullYear();
let ok;
if (user.age > 30) {
ok = true;
}
好代碼:
const MAX_AGE = 30;
let daysSinceLastVisit = 10;
let currentYear = new Date().getFullYear();
...
const isUserOlderThanAllowed = user.age > MAX_AGE;
不要給變量添加額外不需要的單詞
壞代碼:
let nameValue;
let theProduct;
好代碼:
let name;
let product;
不要依賴從上下文才能了解變量的意思
壞代碼:
const ans = ["Chongchong", "maomaochong", "bollworm"];
ans.forEach(an => {
doSomething();
doSomethingElse();
// ...
// 等等,這個(gè)u是干嘛用的擎颖?
register(an);
});
好代碼:
const animals = ["Chongchong", "maomaochong", "bollworm"];
animals.forEach(animal => {
doSomething();
doSomethingElse();
// ...
// ...
register(animal);
});
不添加多余的上下文
壞代碼:
const user = {
userName: "Chongchong",
userNameAbb: "CC",
userAge: "28"
};
...
user.userName;
好代碼:
const user = {
Name: "Chongchong",
NameAbb: "CC",
userAge: "28"
};
...
user.userName;
函數(shù)
使用長(zhǎng)而具有描述性的函數(shù)名榛斯。
由于函數(shù)一般來說表示某種行為,函數(shù)名稱應(yīng)該是動(dòng)詞或短??語搂捧,這樣可以顯示功能以及參數(shù)的意義驮俗。
壞代碼:
function notif(user) {
// 代碼邏輯
}
好代碼:
function notifyUser(emailAddress){
//代碼邏輯
}
避免大量使用參數(shù)。
理想情況下允跑,函數(shù)應(yīng)該指定兩個(gè)或更少的參數(shù)王凑。參數(shù)越少搪柑,函數(shù)單元測(cè)試就越容易。
壞代碼:
function getUsers(fields, fromDate, toDate) {
//代碼邏輯
}
好代碼:
function getUsers({ fields, fromDate, toDate }) {
// 碼邏輯
}
getUsers({
fields: ['name', 'surname', 'email'],
fromDate: '2019-05-22',
toDate: '2019-05-31'
});
使用默認(rèn)參數(shù)索烹,不用條件
壞代碼:
function createShape(type) {
const shapeType = type || "circle";
// ...
}
好代碼:
function createShape(type = "circle") {
// ...
}
一個(gè)函數(shù)做一件事工碾。避免在單個(gè)函數(shù)中執(zhí)行多個(gè)操作,多種邏輯
壞代碼:
function notifyUsers(users) {
users.forEach(user => {
const userRecord = database.lookup(user);
if (userRecord.isVerified()) {
notify(user);
}
});
}
好代碼:
function notifyVerifiedUsers(users) {
users.filter(isUserVerified).forEach(notify);
}
function isUserVerified(user) {
const userRecord = database.lookup(user);
return userRecord.isVerified();
}
使用Object.assign配置默認(rèn)對(duì)象
壞代碼:
const shapeConfig = {
type: "cube",
width: 200,
height: null
};
function createShape(config) {
config.type = config.type || "cube";
config.width = config.width || 250;
config.height = config.width || 250;
}
createShape(shapeConfig);
好代碼:
const shapeConfig = {
type: "cube",
width: 200
};
function createShape(config) {
config = Object.assign(
{
type: "cube",
width: 250,
height: 250
},
config
);
...
}
createShape(shapeConfig);
不要使用標(biāo)志作為參數(shù)。
壞代碼:
function createFile(name, isPublic) {
if (isPublic) {
fs.create(`./public/${name}`);
} else {
fs.create(name);
}
}
好代碼:
function createFile(name) {
fs.create(name);
}
function createPublicFile(name) {
createFile(`./public/${name}`);
}
不要讓全局變量/函數(shù)污染
如果需要擴(kuò)展現(xiàn)有對(duì)象百姓,請(qǐng)使用ES類和繼承渊额,不要在對(duì)象原型鏈上創(chuàng)建函數(shù)。
壞代碼:
Array.prototype.myFunc = function myFunc() {
// 代碼邏輯
};
**好代碼:**
class SuperArray extends Array {
myFunc() {
//代碼邏輯
}
}
條件
不要用否定句
壞代碼:
function isUserNotBlocked(user) {
//代碼邏輯
}
if (!isUserNotBlocked(user)) {
//代碼邏輯
}
好代碼:
function isUserBlocked(user) {
//代碼邏輯
}
if (isUserBlocked(user)) {
//代碼邏輯
}
使用布爾變量直接判斷垒拢,而不是條件語句
壞代碼:
if (isValid === true) {
//代碼邏輯
}
if (isValid === false) {
//代碼邏輯
}
好代碼:
if (isValid) {
//代碼邏輯
}
if (!isValid) {
//代碼邏輯
}
避免使用條件旬迹,用多態(tài)和繼承。
壞代碼:
class Car {
// ...
getMaximumSpeed() {
switch (this.type) {
case "Ford":
return this.someFactor() + this.anotherFactor();
case "Benz":
return this.someFactor();
case "BYD":
return this.someFactor() - this.anotherFactor();
}
}
}
好代碼:
class Car {
// ...
}
class Ford extends Car {
// ...
getMaximumSpeed() {
return this.someFactor() + this.anotherFactor();
}
}
class Benz extends Car {
// ...
getMaximumSpeed() {
return this.someFactor();
}
}
class BYD extends Car {
// ...
getMaximumSpeed() {
return this.someFactor() - this.anotherFactor();
}
}
ES類
類是JavaScript中的新的語法糖求类。除了語法不同外奔垦,其他都和prototype一樣工作。使用ES類可以讓你的代碼更加簡(jiǎn)潔清晰仑嗅。
壞代碼:
const Person = function(name) {
if (!(this instanceof Person)) {
throw new Error("Instantiate Person with `new` keyword");
}
this.name = name;
};
Person.prototype.sayHello = function sayHello() { /**/ };
const Student = function(name, school) {
if (!(this instanceof Student)) {
throw new Error("Instantiate Student with `new` keyword");
}
Person.call(this, name);
this.school = school;
};
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.printSchoolName = function printSchoolName() { /**/ };
好代碼:
class Person {
constructor(name) {
this.name = name;
}
sayHello() {
/* ... */
}
}
class Student extends Person {
constructor(name, school) {
super(name);
this.school = school;
}
printSchoolName() {
/* ... */
}
}
使用方法鏈接
許多庫(kù)如jQuery和Lodash都使用該模式宴倍。因此张症,該方法可以讓的代碼簡(jiǎn)潔仓技。在主類中,只需在每個(gè)函數(shù)的末尾返回"this"俗他,就可以將更多的類方法鏈接到該方法脖捻。
壞代碼:
class Person {
constructor(name) {
this.name = name;
}
setSurname(surname) {
this.surname = surname;
}
setAge(age) {
this.age = age;
}
save() {
console.log(this.name, this.surname, this.age);
}
}
const person = new Person("Chongchong");
person.setSurname("CC");
person.setAge(29);
person.save();
好代碼:
class Person {
constructor(name) {
this.name = name;
}
setSurname(surname) {
this.surname = surname;
return this;
}
setAge(age) {
this.age = age;
return this;
}
save() {
console.log(this.name, this.surname, this.age);
return this;
}
}
const person = new Person("Chongchong")
.setSurname("CC")
.setAge(29)
.save();
其他
通常情況下,盡量不要寫不要重復(fù)代碼兆衅,不要寫不使用的函數(shù)和死代碼地沮。
出于歷史原因,可能會(huì)遇到重復(fù)的代碼羡亩。例如摩疑,有兩段你略有不同的代碼,但是有很多共同的邏輯畏铆,為省事或者趕工期雷袋,導(dǎo)致你復(fù)制了大段代碼,略做小改然后使用了辞居。針對(duì)這種代碼楷怒,后期一定要及早抽象出相同邏輯部分刪除重復(fù)代碼越早越好,不要欠死賬瓦灶,不然后越積越多就不好處理了鸠删。
關(guān)于死代碼,碼如其名贼陶。就是啥事不干刃泡,刪了可能引入錯(cuò)誤巧娱,這和上面的一樣處理,及早處理烘贴,不用了就早處理家卖,早刪除。
結(jié)論
上面只是代碼整潔的部分原理庙楚,而且個(gè)別條款也可能需要商榷上荡。這些大部分理論來源于《代碼整潔之道》
這本書。有什么建議意見請(qǐng)回復(fù)馒闷,一起學(xué)習(xí)討論酪捡。