《代码整洁之道》是由Robert C. Martin(也被称为“Uncle Bob”)所著的一本经典编程书籍,专注于如何编写可维护、易读且高质量的代码。以下是一个关于这本书的阅读笔记,结合实际的JavaScript代码示例。
// 不好的命名
let d;
function ld() {}
// 好的命名
let daysSinceModification;
function loadDocument() {}
// 不好的函数:
function processOrder(order) {
if (order.isValid()) {
let total = 0;
for (let item of order.items) {
total += item.price;
}
order.total = total;
if (total > 100) {
order.discount = total * 0.1;
} else {
order.discount = 0;
}
saveOrder(order);
}
}
// 好的函数:
function processOrder(order) {
if (!order.isValid()) return;
calculateTotal(order);
applyDiscount(order);
saveOrder(order);
}
function calculateTotal(order) {
order.total = order.items.reduce((sum, item) => sum + item.price, 0);
}
function applyDiscount(order) {
order.discount = order.total > 100 ? order.total * 0.1 : 0;
}
// 重复的代码
function getUserInfo(userId) {
// fetch user info from database
let user = database.fetchUser(userId);
return {
id: user.id,
name: user.name,
email: user.email
};
}
function getProductInfo(productId) {
// fetch product info from database
let product = database.fetchProduct(productId);
return {
id: product.id,
name: product.name,
price: product.price
};
}
// 抽象后的代码:
function fetchInfo(type, id) {
let item = database[`fetch${type}`](id);
return {
id: item.id,
name: item.name,
...type === 'User' && { email: item.email },
...type === 'Product' && { price: item.price }
};
}
let userInfo = fetchInfo('User', userId);
let productInfo = fetchInfo('Product', productId);
// 不好的错误处理:
function readFile(filePath) {
if (fs.existsSync(filePath)) {
let fileContent = fs.readFileSync(filePath, 'utf8');
return fileContent;
} else {
return null;
}
}
// 好的错误处理:
function readFile(filePath) {
try {
return fs.readFileSync(filePath, 'utf8');
} catch (error) {
console.error(`Error reading file from disk: ${error}`);
throw error;
}
}
《代码整洁之道》不仅仅是一本关于编码技巧的书,更是一本关于编程心态的指南。通过遵循这些原则,可以编写出更具可读性、可维护性的代码,使团队协作更加顺畅,代码质量更高。希望这些阅读笔记和代码示例对你有所帮助!
因篇幅问题不能全部显示,请点此查看更多更全内容