JavaScript 代码整洁之道:综合指南🚀
编写简洁的代码是任何开发者的必备技能。简洁的代码不仅仅是让你的代码能够运行,更在于让它优雅、高效地运行,并且让其他开发者(包括未来的你自己)能够轻松理解和维护。在本指南中,我们将探讨编写简洁 JavaScript 代码的原则和最佳实践。
什么是干净代码?
干净的代码是这样的:
- 可读性:一目了然
- 可维护:易于修改和调试
- 可重复使用:可重新用于不同的场景
- 可测试:易于编写单元测试
- 可扩展:可以增长而不会变得复杂
1. 变量:整洁代码的基石
- 使用有意义的变量名
您的变量名称应该清楚地表明其目的和上下文。
// 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);
2. 对象:清晰地组织数据
- 使用 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;
}
}
3. 函数:整洁代码的核心
- 保持功能精简且专注
每个函数应该只做一件事。
// 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) { /* ... */ }
4. 注释:何时以及如何使用它们
- 编写自文档代码
您的代码应该足够清晰,不需要大量的注释。
// 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);
5.测试:确保代码质量
- 先写测试(TDD)
考虑在实现功能之前编写测试。
// Example test
describe('User Authentication', () => {
it('should successfully login with valid credentials', () => {
const user = new User('test@example.com', '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');
});
});
6. 现代 JavaScript 特性,让代码更简洁
- 使用可选链式调用
// 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