資料泥團 (Data Clumps)

★★★★★Draft

FromRefactoring

📚 From the Books

資料泥團 (Data Clumps)Code Smells

有幾筆資料老是成群結隊出現——同一組欄位在多個類別現身、同一串參數在多個函式簽章裡反覆出現。它們其實想成為一個物件。

🧠 Why It's a Problem

NOTE

對應重構是把這群資料提取為獨立類別(Extract Class);當它們是出現在參數列裡時,可以先做 Parameter Object。

⚖️ Refactoring

Extract Class:辨認出總是綁在一起的那組資料,替它建一個有名字的類別。

前 — 座標四個值到處一起傳
function distance(x1, y1, x2, y2) {
  return Math.hypot(x2 - x1, y2 - y1);
}
function midpoint(x1, y1, x2, y2) {
  return { x: (x1 + x2) / 2, y: (y1 + y2) / 2 };
}

xy 永遠一起出現,卻永遠是兩個裸值。

後 — 提取成一個有名字的類別
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

function distance(a, b) {
  return Math.hypot(b.x - a.x, b.y - a.y);
}
function midpoint(a, b) {
  return new Point((a.x + b.x) / 2, (a.y + b.y) / 2);
}

Point 這個概念終於有了名字;簽章變短,之後跟座標相關的行為也有地方可放。

🔑 Takeaways

✍️ My Notes

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

📖 Further Reading