情境
有時候會用編號決定畫面如何顯示或是現在狀態…
// bill_status 記錄訂單目前狀態
// 分別為...
bill_status = 0; // 初始訂單, 預設值
bill_status = 1; // 訂單未完成
bill_status = 2; // 訂單已付款
bill_status = 3; // 訂單已退款
程式碼不多的時候還好, 但如果如果程式碼有幾千行或是程式散落各處…
// 光是看到這樣的程式, 很難知道 `2` 代表的意思...
.
.
.
bill_status = 2;
.
.
定義 Const
const BILL_STATUS_DEFAULT = 0;
const BILL_STATUS_UNPAID = 1;
const BILL_STATUS_PAID = 2;
const BILL_STATUS_REFUND = 3;
// usage
bill_status = BILL_STATUS_PAID; // 訂單已付款
bill_status = BILL_STATUS_REFUND; // 訂單已退款
使用 const 取代原來直接使用數字, 未來在看 code 的時候也能比較快速暸解這個變數想表達什麼以及設定他的目地
結論
- 理想上所有魔術數字都設定用 const 替換, 但是宣告、替換也是一個工
建議等這個魔術重覆變了兩、三次再這麼做~ - 效能上的 tradeoff 個人認為可以忽略
ref.
https://refactoring.guru/replace-magic-number-with-symbolic-constant
更多魔術數字例子
什麼是魔術數字(magic number