過大的類別 (Large Class)

★★★★★Draft

FromRefactoring

📚 From the Books

過大的類別 (Large Class)Code Smells

一個類別欄位太多、職責太雜——它想同時做太多事。太多欄位,常代表裡面其實藏著好幾個更小的類別等著被拆出來。

🧠 Why It's a Problem

NOTE

對應重構是拆解為子類別或元件:把成群相關的欄位與方法提取成新類別(Extract Class)。

⚖️ Refactoring

Extract Class:找出類別裡「總是綁在一起」的一組欄位與方法,把它們搬進一個新類別。

前 — 一個類別塞了聯絡方式又塞帳務
class Customer {
  // 聯絡方式
  areaCode;
  phoneNumber;
  formatPhone() {}
  // 帳務地址
  billingStreet;
  billingCity;
  billingZip;
  formatAddress() {}
}

Customer 同時管電話與地址——兩組本可獨立的職責擠在一起。

後 — 把成群的欄位與行為提取成新類別
class Telephone {
  constructor(areaCode, number) {
    this.areaCode = areaCode;
    this.number = number;
  }
  format() {}
}
class Address {
  constructor(street, city, zip) {
    this.street = street;
    this.city = city;
    this.zip = zip;
  }
  format() {}
}

class Customer {
  telephone; // Telephone
  billing; // Address
}

Customer 瘦下來,只協調兩個更小、各司其職的類別。

🔑 Takeaways

✍️ My Notes

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

📖 Further Reading

🔗 Dive Deeper