編寫乾淨的程式碼是任何開發人員的必備技能。乾淨的程式碼不僅僅是讓你的程式碼可以工作,它還意味著讓它優雅、有效率地工作,並且讓其他開發人員(包括你未來的自己)可以輕鬆理解和維護。在本綜合指南中,我們將探討編寫乾淨 JavaScript 程式碼的原則和最佳實務。
乾淨的程式碼是這樣的:
可讀性:一目了然
可維護:修改和除錯簡單
可重複使用:可重新用於不同的場景
可測試:易於編寫單元測試
可擴展:可以增長而不會變得複雜
- 使用有意義的變數名
您的變數名稱應該清楚地表明其目的和上下文。
// Bad
const d = new Date();
let u = getUser();
const arr = ['Apple', 'Banana', 'Orange'];
// Good
const currentDate = new Date();
let currentUser = getUser();
const fruitList = ['Apple', 'Banana', 'Orange'];
- 使用常數作為固定值
當值不會改變時,請使用const
而不是let
或var
。
// Bad
var API_ENDPOINT = 'https://api.example.com';
var MAX_ITEMS = 100;
// Good
const API_ENDPOINT = 'https://api.example.com';
const MAX_ITEMS = 100;
- 保持一致的命名約定
在整個程式碼庫中使用一致的命名模式。
// Bad - Inconsistent naming
getUserInfo()
getClientData()
getCustomerRecord()
// Good - Consistent naming
getUser()
updateUser()
deleteUser()
- 使用可搜尋的名稱
使您的變數和常數易於搜尋。
// Bad
setTimeout(doSomething, 86400000);
// Good
const MILLISECONDS_IN_A_DAY = 86400000;
setTimeout(doSomething, MILLISECONDS_IN_A_DAY);
- 使用 Getters 和 Setters
使用 getter 和 setter 封裝物件屬性。
// Bad
class User {
constructor(name) {
this.name = name;
}
}
// Good
class User {
#name; // Private field
constructor(name) {
this.#name = name;
}
getName() {
return this.#name;
}
setName(name) {
this.#name = name;
}
}
- 實作私有成員
使用私有欄位和方法來保護物件資料。
class BankAccount {
#balance = 0; // Private field
deposit(amount) {
if (this.#validateAmount(amount)) {
this.#balance += amount;
}
}
#validateAmount(amount) { // Private method
return amount > 0;
}
}
- 保持功能小而專注
每個函數應該只做一件事。
// Bad
function processUserData(user) {
validateUser(user);
updateUserInDatabase(user);
sendWelcomeEmail(user);
updateUIWithUserData(user);
}
// Good
function processUserData(user) {
if (validateUser(user)) {
saveUserData(user);
}
}
function saveUserData(user) {
updateUserInDatabase(user)
.then(sendWelcomeEmail)
.then(updateUIWithUserData);
}
- 限制函數參數
使用物件傳遞多個參數。
// Bad
function createUser(firstName, lastName, email, age, location) {
// ...
}
// Good
function createUser(userConfig) {
const { firstName, lastName, email, age, location } = userConfig;
// ...
}
- 使用描述函數名稱
函數名稱應該清楚描述其功能。
// Bad
function proc(data) { /* ... */ }
// Good
function processUserPayment(paymentData) { /* ... */ }
- 編寫自文件程式碼
您的程式碼應該足夠清晰,不需要大量的註釋。
// Bad
// Check if user is adult
if (user.age >= 18) { /* ... */ }
// Good
const isAdult = user.age >= 18;
if (isAdult) { /* ... */ }
- 使用註解來表達複雜的邏輯
評論應該解釋“為什麼”而不是“什麼”。
// Bad
// Iterate through users
users.forEach(user => { /* ... */ });
// Good
// Filter inactive users before sending notifications to avoid
// overwhelming users who haven't logged in for 30+ days
const activeUsers = users.filter(user => user.lastLogin > thirtyDaysAgo);
- 首先編寫測試(TDD)
考慮在實作功能之前編寫測試。
// Example test
describe('User Authentication', () => {
it('should successfully login with valid credentials', () => {
const user = new User('[email protected]', 'password123');
expect(user.login()).toBeTruthy();
});
});
- 測試邊緣情況
始終測試邊界條件和錯誤情況。
describe('Array Utility', () => {
it('should handle empty arrays', () => {
expect(processArray([])).toEqual([]);
});
it('should handle null input', () => {
expect(() => processArray(null)).toThrow('Invalid input');
});
});
- 使用可選鍊式呼叫
// Bad
const streetName = user && user.address && user.address.street;
// Good
const streetName = user?.address?.street;
- 利用解構
// Bad
const firstName = user.firstName;
const lastName = user.lastName;
// Good
const { firstName, lastName } = user;
- 實現預設參數
// Bad
function greet(name) {
name = name || 'Guest';
return `Hello, ${name}!`;
}
// Good
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
編寫乾淨的程式碼是一個不斷改進的過程。這不僅是遵守規則,而是要培養一種重視清晰度、簡單性和可維護性的思考方式。記住:
首先為人類編寫程式碼,其次為電腦編寫程式碼
保持函數小而專注
對變數和函數使用有意義的名稱
徹底測試
定期重構
保持編碼風格的一致性
透過遵循這些原則並不斷改進您的方法,您編寫的程式碼不僅具有功能性,而且真正專業且可維護。
https://www.freecodecamp.org/news/the-clean-code-handbook/?ref=dailydev
https://www.youtube.com/watch?v=b9c5GmmS7ks&list=PLWKjhJtqVAbkK24EaPurzMq0-kw5U9pJh&index=1
原文出處:https://dev.to/alaa-samy/clean-code-in-javascript-a-comprehensive-guide-152j