關於 Clean Code 的小知識點
命名建議
- 直接中翻英設定名稱(不會的單字 Google 翻譯)
- 如果單字超過一個字詞,可用小駝峯寫法(第二個單字開始,將開頭的英文字母改成大寫)
- 布林值可以用 is 開頭
- 陣列可以用複數英文命名(比如 colors/products/orders 等等,直接以單字的複數當名稱)
- 函式使用動詞作為開頭(業界常見使用 get/set/update/add/remove/is/do 等等作為開頭)
使用有意義且可閱讀的變數/函式名稱
const arr = ['red', 'blue', 'green'];
const data = ['red', 'blue', 'green'];
const colors = ['red', 'blue', 'green'];
const colorList = ['red', 'blue', 'green'];
const colorData = ['red', 'blue', 'green'];
const colorArray = ['red', 'blue', 'green'];
const status = "disabled";
const buttonStatus = "disabled";
function updateInfo(info, data) {
...
}
function mergeInfoWithNewData(existingInfo, newData) {
...
}
函數的參數少於 2 個較佳(可以把有關連的參數寫成一個物件)
function addProduct(name, price, quantity) {
const id = Date.now();
cart.push({
id: id,
productName: name,
price: price,
quantity: quantity
});
}
addProduct('Banana', 1, 1 );
function addProduct({ name, price, quantity }) {
const id = Date.now();
cart.push({
id: id,
productName: name,
price: price,
quantity: quantity
});
}
addProduct({ name: 'Banana', price: 1, quantity: 1 });
函式單一性(一個函式只做一件事)
function printBMI(weight, height) {
const bmi = (weight / ((height / 100) * (height / 100))).toFixed(2);
let state = '';
if (bmi < 18.5) {
state = 'overThin';
} else if (bmi < 24) {
state = 'normal';
} else if (bmi < 27) {
state = 'overWeight';
} else if (bmi < 30) {
state = 'mildFat';
} else if (bmi < 35) {
state = 'moderateFat';
} else if (bmi >= 35) {
state = 'severeFat';
}
if (!state) {
return '您的數值輸入錯誤,請重新輸入';
}
console.log(`您的 BMI 數值為 ${bmi}, 體重狀態屬於 ${state}。`)
}
function calculateBmi(weight, height) {
return (weight / ((height / 100) * (height / 100))).toFixed(2);
}
function getBmiState(bmi) {
if (bmi < 18.5) {
return 'overThin';
} else if (bmi < 24) {
return 'normal';
} else if (bmi < 27) {
return 'overWeight';
} else if (bmi < 30) {
return 'mildFat';
} else if (bmi < 35) {
return 'moderateFat';
} else if (bmi >= 35) {
return 'severeFat';
} else {
return '';
}
}
function printBMI(weight, height) {
const bmi = calculateBmi(weight, height);
const state = getBmiState(bmi);
if (!state) {
return '您的數值輸入錯誤,請重新輸入';
}
console.log(`您的 BMI 數值為 ${bmi}, 體重狀態屬於 ${state}。`)
}
if/else 條件判斷過多時,可視情況寫成物件使用
function getStatusMessage(status) {
if (status === 'success') {
return 'Operation was successful.';
} else if (status === 'error') {
return 'An error occurred.';
} else if (status === 'loading') {
return 'Loading...';
} else {
return 'Unknown status.';
}
}
const statusMessages = {
'success': 'Operation was successful.',
'error': 'An error occurred.',
'loading': 'Loading...',
'default': 'Unknown status.'
};
function getStatusMessage(status) {
return statusMessages[status] || statusMessages['default'];
}