Js程式碼簡潔之道
簡介
如果你關注程式碼本身和程式碼的編寫方式,而不是隻關心它是否能工作,那麼你寫程式碼是有一定的水準。專業開發人員將為未來的自己和“其他人”編寫程式碼,而不僅僅只編寫當前能工作就行的程式碼。
在此基礎上,簡潔程式碼可以定義為自解釋的、易於人理解的、易於更改或擴充套件的程式碼。
以下列表一些好編寫方式,僅供參考,當然,如果你有更好的方式,歡迎留言。
1. 強型別檢查
用===代替 ==
// 如果處理不當,它會極大地影響程式邏輯。這就像,你想向左走,但由於某種原因,你向右走
0 == false // true
0 === false // false
2 == "2" // true
2 === "2" // false
// 例子
const value = "500";
if (value === 500) {
console.log(value);
// 條件不成立,不會進入
}
if (value === "500") {
console.log(value);
// 條件成立,會進入
}
2.變數
用知名其意的方式為變數命名,通過這種方式,當一個人看到它們時,易於搜尋和理解。
不好的方式:
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 users = ["John", "Marco", "Peter"];
users.forEach(u => {
doSomething();
doSomethingElse();
// ...
// ...
// ...
// ...
// 當上面程式碼很多的時候 ,這 `u` 是什麼鬼
register(u);
});
好的方式:
const users = ["John", "Marco", "Peter"];
users.forEach(user => {
doSomething();
doSomethingElse();
// ...
// ...
// ...
// ...
register(user);
});
不要新增不必要的上下文。
不好的方式:
const user = {
userName: "John",
userSurname: "Doe",
userAge: "28"
};
...
user.userName;
好的方式:
const user = {
name: "John",
surname: "Doe",
age: "28"
};
...
user.name;
3.函式
使用長而具有描述性的名稱。 考慮到函式表示某種行為,函式名稱應該是動詞或短語,用以說明其背後的意圖以及引數的意圖。 函式的名字應該說明他們做了什麼。
不好的方式:
function notif(user) {
// implementation
}
好的方式:
function notifyUser(emailAddress) {
// implementation
}
避免使用大量引數。 理想情況下,函式應該指定兩個或更少的引數。 引數越少,測試函式就越容易,引數多的情況可以使用物件。
不好的方式:
function getUsers(fields, fromDate, toDate) {
// implementation
}
好的方式:
function getUsers({ fields, fromDate, toDate }) {
// implementation
}
getUsers({
fields: ['name', 'surname', 'email'],
fromDate: '2019-01-01',
toDate: '2019-01-18'
});
使用預設引數替代 || 操作
不好的方式:
function createShape(type) {
const shapeType = type || "cube";
// ...
}
好的方式:
function createShape(type = "cube") {
// ...
}
一個函式應該只做一件事,不要在一個函式中執行多個操作。
不好的方式:
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設定物件預設值。
不好的方式:
const shapeConfig = {
type: "cube",
width: 200,
height: null
};
function createShape(config) {
config.type = config.type || "cube";
config.width = config.width || 250;
config.height = config.height|| 250;
}
createShape(shapeConfig);
好的方式:
const shapeConfig = {
type: "cube",
width: 200
// Exclude the 'height' key
};
function createShape(config) {
config = Object.assign(
{
type: "cube",
width: 250,
height: 250
},
config
);
...
}
createShape(shapeConfig);
不要使用標誌作為引數,因為它們告訴函式做的比它應該做的多。
不好的方式:
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}`);
}
不要汙染全域性變數。 如果需要擴充套件現有物件,請使用ES類和繼承,而不是在原生物件的原型鏈上建立函式。
不好的方式:
Array.prototype.myFunc = function myFunc() {
// implementation
};
好的方式:
class SuperArray extends Array {
myFunc() {
// implementation
}
}
廣州VI設計公司https://www.houdianzi.com
4. 條件
避免使用反面條件。
不好的方式:
function isUserNotBlocked(user) {
// implementation
}
if (!isUserNotBlocked(user)) {
// implementation
}
好的方式:
function isUserBlocked(user) {
// implementation
}
if (isUserBlocked(user)) {
// implementation
}
使用條件簡寫。這可能微不足道,但值得一提。僅對布林值使用此方法,並且如果你確信該值不會是undefined 或null的,則使用此方法。
不好的方式:
if (isValid === true) {
// do something...
}
if (isValid === false) {
// do something...
}
好的方式:
if (isValid) {
// do something...
}
if (!isValid) {
// do something...
}
儘可能避免條件句,而是使用多型性和繼承。
不好的方式:
class Car {
// ...
getMaximumSpeed() {
switch (this.type) {
case "Ford":
return this.someFactor() + this.anotherFactor();
case "Mazda":
return this.someFactor();
case "McLaren":
return this.someFactor() - this.anotherFactor();
}
}
}
好的方式:
class Car {
// ...
}
class Ford extends Car {
// ...
getMaximumSpeed() {
return this.someFactor() + this.anotherFactor();
}
}
class Mazda extends Car {
// ...
getMaximumSpeed() {
return this.someFactor();
}
}
class McLaren extends Car {
// ...
getMaximumSpeed() {
return this.someFactor() - this.anotherFactor();
}
}
5. 類
class 是JavaScript中新的語法糖。一切工作就像以前的原型,只是它現在看起來不同,你應該更喜歡他們比ES5普通功能。
不好的方式:
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() {
/* ... */
}
}
使用連結。許多庫(如jQuery和Lodash)都使用這種模式。在類中,只需在每個函式的末尾返回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("John");
person.setSurname("Doe");
person.setAge(29);
person.save();
好的方式:
class Person {
constructor(name) {
this.name = name;
}
setSurname(surname) {
this.surname = surname;
// Return this for chaining
return this;
}
setAge(age) {
this.age = age;
// Return this for chaining
return this;
}
save() {
console.log(this.name, this.surname, this.age);
// Return this for chaining
return this;
}
}
const person = new Person("John")
.setSurname("Doe")
.setAge(29)
.save();
總結
這只是改進程式碼的一小部分。一般生活入,這裡所說的原則是人們通常不遵守的原則。他們嘗試著去做,但出於各種原因,就沒有堅持下去。也許在專案開始時,程式碼是簡潔的,但是當要在截止日期前完成時,這些原則常常被忽略,並被轉移到“TODO”或“REFACTOR”部分。在這一點上,你的客戶更希望您在最後期限之前完成任務,而不是編寫簡潔的程式碼。