名稱長度與作用域 (Length & Scope)

★★★★★Draft

FromCode CompleteAPoSDClean Code

📚 From the Books

名稱長度與作用域 (Length & Scope)Naming

名字該多長?答案不是固定的,而是跟著作用域走:一個變數活得越久、走得越遠,讀者能從上下文推出它的機會就越小,名字就得越具描述性。作用域小到幾行內看得完,i 就夠了;跨越整個模組,就得把意義寫進名字。

🧠 Why It Matters

TIP

Code Complete 的「電話測試」:如果你沒辦法在電話裡把程式碼唸給同事聽,名字就取壞了。用 xPos 而非 xPstn——名字必須唸得出來。

⚖️ Case Study

前 — 作用域大卻用短名,還埋了魔術數字
function f(d) {
  let r = 0;
  for (const x of d) {
    if (x.t > 30) r += x.v * 0.07; // 30?0.07?搜尋 "0.07" 撈到一堆無關結果
  }
  return r;
}

fdrx 全是跨越整個函式的作用域卻用單字母;300.07 是無法搜尋、無語意的魔術數字。

後 — 長度配合作用域,常數具名可搜尋
const OVERDUE_DAYS = 30;
const LATE_FEE_RATE = 0.07;

function totalLateFees(invoices) {
  let feesTotal = 0;
  for (const invoice of invoices) {
    if (invoice.daysOverdue > OVERDUE_DAYS) {
      feesTotal += invoice.amount * LATE_FEE_RATE;
    }
  }
  return feesTotal;
}

跨函式作用域的變數拿到描述性名字;魔術數字換成可搜尋的具名常數。注意迴圈內若要短名,invoice 這種一眼可懂的仍優於 x

WARNING

計算值限定詞(Total、Count、Sum、Average、Index)放在名字末尾且全專案一致:revenueTotalexpenseAverage。特別小心 Num——numCustomers(總數)與 customerNum(索引)語意相反,建議改用 CountTotal 表總數、Index 表索引。

🔑 Takeaways

✍️ My Notes

No notes yet — jot your takeaways or Q&A here.

📖 Further Reading