OOP 4 เสาหลัก

encapsulation, abstraction, inheritance, polymorphism ฟังแล้วเหมือนท่องจำ มาดูบนร้านส่งพัสดุร้านเดียวแทน แล้วจะเห็นว่าแต่ละข้อกันปัญหาอะไร และทำไมสืบทอดไปเรื่อย ๆ ถึงพัง

ระดับ: พื้นฐานดู 17 ขั้น · ~75 วินาทีถามราคา ใส่ชิ้นส่วน แอบแก้ statusจำ 3 คำถาม · 8 การ์ดเทียบ inheritance · compositionTypeScript · Java · Kotlin · Python · Go

สิ่งที่จะได้

  • ซ่อน state ไว้หลัง method ที่เช็กกฎได้ อย่าง deliver() ที่ไม่ยอมถ้ายังไม่ pickUp()
  • บอก encapsulation กับ abstraction ออก: อันหนึ่งปกป้องข้างใน อีกอันเลือกว่าข้างนอกเห็นอะไร
  • ใช้ polymorphism ให้เรียก quote() แบบเดียวกับทุก courier โดยไม่ต้องมี if เช็กว่าเป็นรถอะไร
  • เห็นตอนที่ subclass เริ่มบาน แล้วเปลี่ยนไปใช้ composition ให้ courier มีชิ้นส่วนแทน

สรุป 1 นาที

กดข้อไหน ภาพข้างล่างจะเล่นขั้นนั้นให้ดู

4เทียบทุกแบบ
class กับ objectแบบ กับของที่สร้างจากแบบ
ร้าน
class Parcel
new Parcel("TH-001", 2) → …
ขั้น 1 / 17 · กดทีละขั้น
0พัสดุที่สร้าง
0ส่งถึงแล้ว
–ราคาล่าสุด
2class ของ courier

ร้าน รถ และพัสดุแต่งขึ้นสำหรับบทนี้ ราคาเป็นตัวเลขสมมุติ ในโรงงาน โต๊ะทำงานคือ class สายพานสีม่วงหัวโปร่งคือ "extends" ส่วนบนถนน ลังคือ object ของพัสดุ และดวงไฟคือการเรียก method

ขั้นที่ 4 · ปล่อยทุกแบบวิ่งพร้อมกัน

เทียบทุกแบบ: Inheritance กับ Composition

ร้านมีรถสองแบบ แล้วงานใหม่ก็เข้ามาทีละอย่าง: ห้องเย็น ประกัน ติดตามสด ส่งด่วน ฝั่งซ้ายใช้ inheritance ต้องมี subclass ทุกแบบผสม ฝั่งขวาใช้ composition ให้ courier มีชิ้นส่วนแทน นับ class ที่ต้องเขียน

ยังไม่มีฟีเจอร์เพิ่ม
Inheritance (เป็น)class ColdInsuredTruck extends Truckclass ทั้งหมด 3 · ฟีเจอร์ถัดไปต้องเขียนเพิ่ม 2

ใช้เมื่อ ของที่เป็นแบบหนึ่งของอีกอย่างจริง ๆ และลำดับชั้นตื้น ไม่ค่อยเปลี่ยน

ไม่ควรใช้เมื่อ ต้องผสมหลายความสามารถ: class บานเป็นทวีคูณ และแก้แม่ทีกระทบลูกทุกตัว

นับแบบตรง ๆ: inheritance = 1 + รถ 2 × 2^ฟีเจอร์, composition = 1 + รถ 2 + ชิ้นส่วนละหนึ่ง · กดช่องไหนก็ได้ ภาพใหญ่ด้านบนจะเปลี่ยนเป็นแบบนั้น พร้อมบอกว่าเหมาะกับงานแบบไหน

สี่หลักในประโยคเดียว

หลักทำอะไรในร้านนี้
Encapsulationซ่อน state แล้วเปิดแค่ประตูที่เช็กกฎstatus แก้ได้แค่ผ่าน pickUp() กับ deliver()
Abstractionให้คนใช้เห็นแค่ที่ต้องใช้ร้านรู้จัก Courier แค่ quote() กับ ship()
Inheritanceลูกได้โค้ดของแม่ไปใช้Motorbike กับ Truck ได้ track() จาก Courier
Polymorphismเรียกเหมือนกัน ตอบคนละแบบquote() ตัวเดียว ได้ราคาตามสูตรของแต่ละรถ

composition มาก่อน inheritance

สืบทอดเมื่อของนั้น "เป็น" แบบหนึ่งของอีกอย่างจริง ๆ และลำดับชั้นตื้น ที่เหลือให้ "มี" ชิ้นส่วนแทน ผสมได้ทุกแบบโดยไม่ต้องเขียน class ใหม่ และแก้ชิ้นหนึ่งไม่ลามไปทั้งต้นไม้

แต่ละภาษาทำไม่เหมือนกัน

Java กับ Kotlin มี private จริงที่ compiler บังคับ TypeScript มี #field ที่ runtime บังคับด้วย Python ไม่มี private จริง ใช้ _ เป็นธรรมเนียม ส่วน Go ไม่มี class เลย ใช้ struct, interface และ embedding และซ่อนข้อมูลต่อ package

ในโค้ดจริง

parcel.ts
// The four ideas of OOP on one small shop: a Parcel guards its status, couriers share tracking and price their own way.
// Run: node parcel.ts   (Node 23.6+; on Node 22: node --experimental-strip-types parcel.ts)
import assert from "node:assert/strict";

type Status = "waiting" | "picked" | "delivered";

class Parcel {
  #status: Status = "waiting"; // encapsulation: nothing outside the class can set it
  readonly id: string;
  readonly kg: number;
  constructor(id: string, kg: number) { this.id = id; this.kg = kg; }
  get status(): Status { return this.#status; }
  pickUp() { if (this.#status !== "waiting") throw new Error("already picked up"); this.#status = "picked"; }
  deliver() { if (this.#status !== "picked") throw new Error("not picked up yet"); this.#status = "delivered"; }
}

// Abstraction: all the shop gets to know about a courier.
interface Courier {
  readonly name: string;
  quote(p: Parcel): number | null; // null: can't take it
  ship(p: Parcel): string;
}

// Inheritance: what every courier shares, written once.
abstract class BaseCourier implements Courier {
  abstract readonly name: string;
  abstract quote(p: Parcel): number | null;
  ship(p: Parcel) { p.pickUp(); return this.track(p); }
  protected track(p: Parcel) { return `${this.name} has ${p.id} (${p.status})`; }
}
class Motorbike extends BaseCourier {
  readonly name = "Motorbike";
  quote(p: Parcel) { return p.kg > 10 ? null : 30 + Math.ceil(p.kg) * 8; }
}
class Truck extends BaseCourier {
  readonly name = "Truck";
  quote(p: Parcel) { return 90 + Math.ceil(p.kg) * 3; }
}

// Polymorphism: one call for every courier; each answers its own way.
const couriers: Courier[] = [new Motorbike(), new Truck()];
const quotes = (p: Parcel) => couriers.map((c) => `${c.name} ${c.quote(p) ?? "can't"}`).join(", ");

const small = new Parcel("TH-001", 2), heavy = new Parcel("TH-002", 20);
assert.equal(quotes(small), "Motorbike 46, Truck 96");
assert.equal(quotes(heavy), "Motorbike can't, Truck 150");
assert.throws(() => small.deliver(), /not picked up/); // the order is guarded
const shipped = couriers[0].ship(small);
small.deliver();
assert.equal(small.status, "delivered"); // small.#status = "picked" would not even compile
console.log(`2 kg: ${quotes(small)} · 20 kg: ${quotes(heavy)} · ${shipped} → delivered`);
รัน: node parcel.ts (Node 23.6+ · Node 22 ใส่ --experimental-strip-types)ผลที่พิมพ์ออกมา: 2 kg: Motorbike 46, Truck 96 · 20 kg: Motorbike can't, Truck 150 · Motorbike has TH-001 (picked) → delivered

ร้านเดียวกัน เขียนห้าภาษา พิมพ์ผลเหมือนกันทุกตัว: status เป็น private (Python ใช้ _ กับ property, Go ซ่อนต่อ package), Courier เป็น interface, track() เขียนครั้งเดียวใน class แม่ แล้ว quote() ของแต่ละรถตอบไม่เหมือนกัน Go ไม่มี class เลยใช้ struct, interface กับ embedding แทน

คำถามที่เจอบ่อย

OOP มีสี่หลักอะไรบ้าง

encapsulation ซ่อน state แล้วเปิดแค่ทางที่เช็กกฎ abstraction ให้คนใช้เห็นแค่ที่ต้องใช้ inheritance ให้ลูกได้โค้ดของแม่ไปใช้ polymorphism คือเรียกแบบเดียวกัน แต่ละตัวตอบตามแบบของตัวเอง

encapsulation กับ abstraction ต่างกันยังไง

encapsulation ปกป้องข้างใน status เป็น private เปลี่ยนได้แค่ผ่าน method ที่เช็กลำดับ abstraction เลือกว่าข้างนอกเห็นอะไร ร้านรู้จัก Courier แค่ quote() กับ ship() ไม่สนว่าวิ่งทางไหน ตัวแรกกันของพัง ตัวหลังกันไม่ให้ต้องรู้เยอะเกิน

polymorphism คืออะไร พูดง่าย ๆ

เรียก method ชื่อเดียวกันกับของคนละแบบ แล้วแต่ละตัวตอบตามแบบของตัวเอง ร้านวนเรียก quote() กับรถทุกคัน มอเตอร์ไซค์กับรถบรรทุกคิดราคาคนละสูตร ของ 20 กก. มอเตอร์ไซค์ก็บอกเองว่ารับไม่ไหว

composition over inheritance หมายความว่าอะไร

inheritance คือ 'เป็น' composition คือ 'มี' ถ้าทำ subclass ทุกแบบผสม ฟีเจอร์สี่อย่างบนรถสองแบบก็ปาไป 33 class ให้ courier มีชิ้นส่วนแทน รวมแค่ 7 class และผสมแบบไหนก็ไม่ต้องเพิ่ม

แล้วเมื่อไหร่ควรใช้ inheritance

ตอนที่ของนั้นเป็นแบบหนึ่งของอีกอย่างจริง ๆ และลำดับชั้นตื้น ไม่ค่อยเปลี่ยน อย่าง Motorbike กับ Truck เป็น Courier แล้วได้ track() ไปใช้ฟรี พอเริ่มต้องผสมหลายความสามารถ นั่นคือสัญญาณให้หันไปใช้ composition

อ่าน: composition มาก่อน inheritance

class กับ object ต่างกันยังไง

class คือแบบ object คือของที่สร้างจากแบบนั้น Parcel บอกว่าพัสดุมีน้ำหนัก มีสถานะ และทำอะไรได้บ้าง ส่วนพัสดุแต่ละกล่องคือ object ที่มีค่าของตัวเอง

private ของแต่ละภาษาเหมือนกันไหม

ไม่เหมือน Java กับ Kotlin มี private จริงที่ compiler บังคับ TypeScript มี #field ที่บังคับตอนรันด้วย Python ไม่มี private จริง มีแค่ธรรมเนียม _ ส่วน Go ไม่มี class เลย ซ่อนกันระดับ package

บทต่อไป

Design patternsระดับ: กลาง

interface, polymorphism กับ composition คือชิ้นส่วน บทต่อไปคือ design pattern ทางแก้มีชื่อที่ประกอบจากพวกนี้ และตอนที่ไม่ควรใช้