用基本型態(字串、數字)硬扛本該是領域概念的東西——電話號碼是 string、金額是 number。改用 Value Object,讓概念有自己的型別,也有安放行為的地方。
🧠 Why It's a Problem
- 概念沒有型別:金額只是個
number,於是貨幣、格式、驗證規則就散落各處,也容易誤用(例如把兩種幣別的數字直接相加)。 - 行為無處可放:跟這個概念相關的運算(格式化、驗證、換算)沒有家,只能到處重複。
- 本章把它歸在資料與變數管理——過度使用基本型態代表業務概念,是系統脆弱的主因之一。
NOTE
對應重構是改為 Value Object:把「一個基本值 + 它的相關規則」包成一個小類別。
⚖️ Refactoring
用 Value Object 取代裸的基本型態,把散落的規則收進這個型別裡。
前 — 金額只是一個 number
class Order {
constructor(amount, currency) {
this.amount = amount; // 裸的 number
this.currency = currency; // 裸的 string
}
}
// 相加時沒有任何東西攔住你把不同幣別加在一起
const total = orderA.amount + orderB.amount;後 — 用 Value Object 承載概念與規則
class Money {
constructor(amount, currency) {
this.amount = amount;
this.currency = currency;
}
plus(other) {
if (other.currency !== this.currency) throw new Error('currency mismatch');
return new Money(this.amount + other.amount, this.currency);
}
format() {
return `${this.currency} ${this.amount.toFixed(2)}`;
}
}
class Order {
constructor(price) {
this.price = price; // price 是一個 Money
}
}「金額」現在有了型別;相加、格式化的規則都收進 Money,誤用(跨幣別相加)當場被擋下。
🔑 Takeaways
- 基本型態偏執的訊號是用 string/number 硬扛一個領域概念。
- 標準解是改為 Value Object:讓概念有型別,也讓相關規則與行為有家可歸。
- 概念一旦有了型別,散落各處的驗證與格式化就能收攏,誤用也更容易被擋下。
No notes yet — jot your takeaways or Q&A here.