Try   HackMD

關於 Clean Code 的小知識點

命名建議

  1. 直接中翻英設定名稱(不會的單字 Google 翻譯)
  2. 如果單字超過一個字詞,可用小駝峯寫法(第二個單字開始,將開頭的英文字母改成大寫)
  3. 布林值可以用 is 開頭
  4. 陣列可以用複數英文命名(比如 colors/products/orders 等等,直接以單字的複數當名稱)
  5. 函式使用動詞作為開頭(業界常見使用 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) { // 計算 BMI const bmi = (weight / ((height / 100) * (height / 100))).toFixed(2); // 獲取 BMI 狀態 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) { // 計算 BMI const bmi = calculateBmi(weight, height); // 獲取 BMI 狀態 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']; }