依戀情結 (Feature Envy)

★★★★Draft

FromRefactoring

📚 From the Books

依戀情結 (Feature Envy)Code Smells

一個函式對「別的類別」的資料,比對自己所在類別的資料更感興趣——它不停地取用另一個物件的欄位來運算。把函式搬到它真正依戀的資料所在的類別,耦合就降下來了。

🧠 Why It's a Problem

TIP

對應重構是 Move Function:把函式搬到它最感興趣的那份資料所在的類別。原則很直白——行為該和它操作的資料待在一起

⚖️ Refactoring

Move Function:辨認出函式最常存取哪個物件的資料,把它移過去。

前 — 方法住錯了家
class Customer {
  discountedTotal(order) {
    // 幾乎只在動 order 的資料,對自己的 Customer 欄位毫無興趣
    const subtotal = order.items.reduce((s, i) => s + i.price * i.qty, 0);
    return subtotal * (1 - order.loyaltyRate);
  }
}

discountedTotal 通篇在讀 order 的欄位,卻掛在 Customer 上。

後 — 把行為搬到資料所在處
class Order {
  discountedTotal() {
    const subtotal = this.items.reduce((s, i) => s + i.price * i.qty, 0);
    return subtotal * (1 - this.loyaltyRate);
  }
}

現在方法和它操作的資料同住 Order,不再跨物件伸手,耦合下降。

🔑 Takeaways

✍️ My Notes

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

📖 Further Reading

🔗 Dive Deeper