基本型態偏執 (Primitive Obsession)

★★★★Draft

FromRefactoring

📚 From the Books

基本型態偏執 (Primitive Obsession)Code Smells

用基本型態(字串、數字)硬扛本該是領域概念的東西——電話號碼是 string、金額是 number。改用 Value Object,讓概念有自己的型別,也有安放行為的地方。

🧠 Why It's a Problem

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

✍️ My Notes

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

📖 Further Reading