หลักการออกแบบซอฟต์แวร์: คู่มือฉบับสมบูรณ์¶
senior engineer เก่ง ๆ ที่คุณนับถือ ทุกคนมีหลักการบางอย่างติดตัว ไม่ใช่กฎใน style guide แต่เป็นสัญชาตญาณที่ได้มาจากการเจ็บจริง เห็นโค้ดปุ๊บก็รู้ทันทีว่ามีอะไรไม่ชอบมาพากล ทั้งที่ยังอธิบายไม่ได้ด้วยซ้ำว่าเพราะอะไร
สัญชาตญาณแบบนี้ฝึกกันได้ หลักการที่รวบรวมไว้ในคู่มือนี้ ก็คือสัญชาตญาณเหล่านั้นที่เขียนออกมาเป็นข้อ ๆ
หลักการออกแบบซอฟต์แวร์เป็น heuristic คือแนวทาง ไม่ใช่กฎตายตัว ไม่มีข้อไหนใช้ได้กับทุกสถานการณ์ แต่พอรวมกันแล้ว คุณจะได้ทั้งภาษากลางไว้คุยเรื่องคุณภาพโค้ด และเข็มทิศไว้ชั่ง trade-off ถ้าซึมซับจนเป็นนิสัย คุณจะเสียเวลาแก้ของเก่าน้อยลง แล้วมีเวลาสร้างของใหม่มากขึ้น
เนื้อหาแบ่งเป็น 4 ชั้น แต่ละชั้นต่อยอดจากชั้นก่อนหน้า:
- Foundational — หลักการพื้นฐานที่ไม่มีวันล้าสมัย developer ทุกคนควรรู้แบบขึ้นใจ
- SOLID — หลักการออกแบบ object-oriented 5 ข้อ พร้อมโค้ด before/after
- Advanced — pattern ขั้นลึกขึ้น ตัวที่ทำให้โค้ดดีกลายเป็นโค้ดชั้นเยี่ยม
- Cloud-Native — หลักการของ distributed system สำหรับ architecture ยุคใหม่
ทำไมหลักการออกแบบถึงสำคัญ¶
โค้ดแย่ไม่ได้เกิดเพราะ developer มักง่าย แต่เพราะการทำซอฟต์แวร์ ยาก จริง ๆ requirement เปลี่ยน deadline บีบเข้ามา ความซับซ้อนก็พอกพูนขึ้นเรื่อย ๆ แบบไม่มีใครทันเห็น ถ้าไม่มีหลักการ ทางลัดทุกครั้งจะทำให้งานชิ้นต่อไปยากขึ้น ถ้ามีหลักการ ระบบที่คุณสร้างจะยัง maintain ได้ แม้ในช่วงที่โดนกดดันหนัก ๆ
ไม่สนหลักการออกแบบแล้วต้องจ่ายจริง และวัดออกมาเป็นตัวเลขได้ด้วย:
THE COMPOUNDING COST OF TECHNICAL DEBT
Week 1: Feature takes 2 days to build (shortcuts taken)
Week 4: Similar feature takes 3 days (must work around week 1 shortcuts)
Week 12: Bug hunt takes 1 week (nobody understands the code anymore)
Week 24: Refactor the whole module (the shortcuts own you now)
Following principles:
Week 1: Feature takes 3 days (principled implementation)
Week 4: Similar feature takes 1 day (reuses clean abstractions)
Week 12: Bug fixed in hours (code is understandable and testable)
Week 24: New feature added cleanly (the design absorbs change)
หลักการในคู่มือนี้จะช่วยให้คุณอยู่ฝั่งที่ดีของกราฟนี้
Part 1: หลักการพื้นฐาน (Foundational Principles)¶
หลักการ 5 ข้อนี้เก่ากว่า SOLID และเป็นฐานของทุกอย่างที่ตามมา ใช้ได้ทุกระดับ ตั้งแต่ function, class, module ไปจนถึงทั้ง system
1. KISS — Keep It Simple, Stupid¶
"ทำทุกอย่างให้ง่ายที่สุดเท่าที่ทำได้ แต่อย่าง่ายจนเกินไป" — Albert Einstein
ความซับซ้อนคือศัตรูของซอฟต์แวร์ ความซับซ้อนที่ไม่จำเป็นทุกชั้น คือ bug ที่รอวันโผล่ คือ junior ที่เข้ามาช่วยงานไม่ได้ และคือ incident ตอนตีสามที่คุณไม่มีวันเข้าใจได้ทั้งหมด
KISS บอกไว้ข้อเดียว: เลือกวิธีที่ง่ายที่สุดที่แก้ปัญหาได้ถูกต้อง
กับดักความซับซ้อน¶
# TRAP 1: Over-engineering a simple problem
# BAD: building a factory + strategy + registry for something that needs an if/else
class DiscountStrategyRegistry:
_strategies: dict[str, 'DiscountStrategy'] = {}
@classmethod
def register(cls, name: str, strategy: 'DiscountStrategy') -> None:
cls._strategies[name] = strategy
@classmethod
def get(cls, name: str) -> 'DiscountStrategy':
if name not in cls._strategies:
raise KeyError(f"Unknown discount strategy: {name}")
return cls._strategies[name]
class DiscountStrategy(ABC):
@abstractmethod
def apply(self, price: float) -> float: ...
class TenPercentDiscount(DiscountStrategy):
def apply(self, price: float) -> float:
return price * 0.90
class TwentyPercentDiscount(DiscountStrategy):
def apply(self, price: float) -> float:
return price * 0.80
# 4 classes, 30 lines to do what this does:
# GOOD: simple and clear — if requirements grow, refactor then
def apply_discount(price: float, discount_type: str) -> float:
discounts = {"ten_percent": 0.90, "twenty_percent": 0.80}
multiplier = discounts.get(discount_type, 1.0)
return price * multiplier
# TRAP 2: Clever one-liners that nobody can read
# BAD: "clever" but unreadable
result = [x for x in (lambda l: (sorted(l), l)[1])(data)
if (lambda v: v > 0 and v % 2 == 0)(x)]
# GOOD: readable — anyone can understand this in 5 seconds
def get_positive_even_numbers(numbers: list[int]) -> list[int]:
return [n for n in numbers if n > 0 and n % 2 == 0]
result = get_positive_even_numbers(data)
วิธีใช้ KISS¶
ก่อนจะเขียนอะไรซับซ้อน ถามตัวเองก่อนว่า "วิธีที่ง่ายที่สุดที่น่าจะใช้ได้คืออะไร?" แล้วทำแบบนั้น ความซับซ้อนค่อยเพิ่มทีหลัง ตอนที่วิธีง่าย ๆ ไม่พอจริง ๆ ไม่ใช่ใส่เผื่อไว้ล่วงหน้าเพราะเดาเอา
Rule of Three สำหรับ abstraction
อย่าเพิ่งทำ abstraction จนกว่าจะเจอ case จริงครบ 3 case เจอ case เดียว เขียนตรง ๆ ไปเลย เจอสอง case อาจแยกเป็น helper พอเจอสาม case ถึงจะเข้าใจ pattern ดีพอที่จะ abstract ได้ถูก
2. DRY — Don't Repeat Yourself¶
"ความรู้ทุกชิ้นในระบบต้องมีที่อยู่หลักเพียงที่เดียว ชัดเจน และเป็นตัวจริง" — Andy Hunt & Dave Thomas, The Pragmatic Programmer
DRY พูดถึง ความรู้ (knowledge) ที่ซ้ำกัน ไม่ใช่แค่โค้ดที่ซ้ำ ถ้า logic เดียวกันอยู่สองที่ พอ requirement เปลี่ยนก็ต้องแก้ทั้งสองที่ แล้วสักวันคุณจะลืมแก้ที่ใดที่หนึ่งแน่นอน
ต้นทุนแฝงของโค้ดซ้ำ¶
# BAD: The shipping cost logic duplicated in two places
class OrderService:
def calculate_order_total(self, order: Order) -> float:
subtotal = sum(item.price * item.quantity for item in order.items)
# Shipping logic here...
if order.destination_country != "US":
shipping = subtotal * 0.15 # 15% for international
elif subtotal >= 50:
shipping = 0 # free domestic over $50
else:
shipping = 5.99 # flat rate domestic
return subtotal + shipping
class QuoteService:
def generate_shipping_quote(self, cart: Cart) -> float:
subtotal = sum(item.price * item.quantity for item in cart.items)
# SAME shipping logic duplicated — if the rules change,
# will you remember to update BOTH places?
if cart.destination_country != "US":
shipping = subtotal * 0.15
elif subtotal >= 50:
shipping = 0
else:
shipping = 5.99
return shipping
# GOOD: One authoritative source for shipping logic
class ShippingCalculator:
INTERNATIONAL_RATE = 0.15
FREE_DOMESTIC_THRESHOLD = 50.00
FLAT_DOMESTIC_RATE = 5.99
def calculate(self, subtotal: float, destination_country: str) -> float:
if destination_country != "US":
return subtotal * self.INTERNATIONAL_RATE
if subtotal >= self.FREE_DOMESTIC_THRESHOLD:
return 0.0
return self.FLAT_DOMESTIC_RATE
class OrderService:
def __init__(self, shipping: ShippingCalculator):
self._shipping = shipping
def calculate_order_total(self, order: Order) -> float:
subtotal = sum(item.price * item.quantity for item in order.items)
return subtotal + self._shipping.calculate(subtotal, order.destination_country)
class QuoteService:
def __init__(self, shipping: ShippingCalculator):
self._shipping = shipping
def generate_shipping_quote(self, cart: Cart) -> float:
subtotal = sum(item.price * item.quantity for item in cart.items)
return self._shipping.calculate(subtotal, cart.destination_country)
ทีนี้ถ้ากฎค่าส่งเปลี่ยน (ซึ่งเปลี่ยนแน่) ก็แก้แค่ที่เดียวพอ
DRY เป็นเรื่องของความรู้ ไม่ใช่โค้ด¶
โค้ดสองก้อนหน้าตาเกือบเหมือนกัน ไม่ได้แปลว่าผิด DRY เสมอไป ถ้าสองก้อนนั้นเป็น ความรู้คนละเรื่อง:
# This is NOT a DRY violation — same structure, different knowledge
def validate_username(username: str) -> bool:
return len(username) >= 3 and username.isalnum()
def validate_product_code(code: str) -> bool:
return len(code) >= 3 and code.isalnum()
วันนี้สอง function นี้บังเอิญโครงสร้างเหมือนกัน แต่การ validate username กับ product code เป็น business rule คนละข้อ วันหนึ่งจะต้องแยกทางกันแน่ ถ้ารวบเป็น function กลางอย่าง validate_alphanumeric_min_3 ก็เท่ากับเอาสองเรื่องที่ไม่เกี่ยวกันมาผูกติดกัน
WET code กับ DRY ผิดที่
WET = "Write Everything Twice" ราคาที่ต้องจ่ายของ WET code คือภาระตอน maintain แต่ถ้าไล่ลบความซ้ำแบบไม่ยั้ง ในโค้ดที่เป็น domain concept คนละตัว คุณจะได้ abstraction ที่ผิดมาแทน ซึ่งแย่กว่าโค้ดซ้ำเสียอีก Sandi Metz พูดไว้ว่า "โค้ดซ้ำยังเสียน้อยกว่า abstraction ที่ผิดเยอะ"
3. YAGNI — You Aren't Gonna Need It¶
"ลงมือ implement ตอนที่ต้องใช้จริงเท่านั้น อย่า implement แค่เพราะคิดว่าเดี๋ยวคงต้องใช้" — Ron Jeffries
YAGNI คือวินัยข้อหนึ่ง: อย่าเพิ่ม functionality จนกว่าจะต้องใช้จริง สร้างตาม requirement ของวันนี้ ไม่ใช่ requirement ที่นึกเอาเองว่าพรุ่งนี้จะมา
ปัญหา Speculative Generality¶
# BAD: building a plugin system "just in case" we need extensibility
class NotificationService:
def __init__(self):
self._channels: dict[str, 'NotificationChannel'] = {}
self._formatters: dict[str, 'MessageFormatter'] = {}
self._rate_limiters: dict[str, 'RateLimiter'] = {}
self._fallback_chain: list[str] = []
# ... 200 more lines of infrastructure for requirements that don't exist
def register_channel(self, name: str, channel: 'NotificationChannel') -> None: ...
def register_formatter(self, name: str, formatter: 'MessageFormatter') -> None: ...
def send(self, user_id: str, message: str, channel: str = "default") -> None: ...
# etc.
# GOOD: build what you need, refactor when requirements actually arrive
class NotificationService:
def __init__(self, smtp_client: SmtpClient):
self._smtp = smtp_client
def send_email(self, to: str, subject: str, body: str) -> None:
self._smtp.send(to=to, subject=subject, body=body)
ต้องส่ง SMS เมื่อไหร่ค่อยเพิ่มตอนนั้น จะทำ plugin system ก็รอให้มี channel ที่สามก่อน ตอนนี้ requirement มีแค่ email ก็ทำแค่ email
ทำไมคนถึงหลุด YAGNI กันบ่อย¶
- กลัว: "ไม่ทำตอนนี้ เดี๋ยวมาเสียดายทีหลัง"
- อีโก้: "architect ตัวจริงเขาต้องออกแบบให้ extensible"
- แผลเก่า: "คราวก่อนไม่ทำไว้ สุดท้ายต้อง rewrite ใหม่หมด"
ทางแก้คือเขียนโค้ดให้สะอาดและมี test ครอบไว้ดี โค้ดแบบนี้ refactor ง่าย เพิ่มของทีหลังเสียน้อยกว่าแบกความซับซ้อนที่ไม่ได้ใช้ไว้ตั้งแต่วันนี้
หาจุดพอดีระหว่าง YAGNI กับ SOLID
YAGNI กับ Open/Closed Principle ดูเหมือนจะขัดกัน OCP บอกให้ "ออกแบบเผื่อ extend" ส่วน YAGNI บอกว่า "อย่าออกแบบจากการเดา"
ทางออกคือใช้ pattern ของ OCP เฉพาะจุดที่คุณ รู้ แน่ว่าต้อง extend (เพราะ requirement บอกไว้ชัด) หรือจุดที่ทำ extension point ได้แทบไม่มีต้นทุน ไม่ต้องใส่ OCP เผื่อไว้ทุก class
4. Separation of Concerns (SoC)¶
"ศิลปะของการเขียนโปรแกรม คือศิลปะของการจัดการความซับซ้อน" — Edsger Dijkstra
concern คือแต่ละแง่มุมของ functionality ในระบบที่แยกเป็นเรื่องของตัวเองได้ Separation of Concerns บอกให้เก็บ concern ที่ต่างกันไว้คนละที่ จะได้เข้าใจ พัฒนา และแก้แต่ละเรื่องได้โดยไม่กระทบกัน
# BAD: one function does everything — business logic, data access, formatting
def process_order(order_id: str) -> str:
# Data access concern
conn = psycopg2.connect("postgresql://...")
cursor = conn.cursor()
cursor.execute("SELECT * FROM orders WHERE id = %s", (order_id,))
row = cursor.fetchone()
# Business logic concern
total = row['subtotal']
if row['membership'] == 'gold':
total *= 0.90
if row['country'] != 'US':
total += total * 0.15
# Persistence concern
cursor.execute(
"UPDATE orders SET total = %s, status = 'processed' WHERE id = %s",
(total, order_id)
)
conn.commit()
# Formatting / presentation concern
return f"<html><body>Order {order_id}: ${total:.2f} processed</body></html>"
พอ requirement เปลี่ยน (ซึ่งเปลี่ยนตลอด) คุณจะไปแก้ตรงไหน? ต้องอ่านทั้งก้อน แก้ logic ส่วนลดทีก็เสี่ยงทำ database query พัง ส่วนโค้ด format HTML ก็จมอยู่กลาง business logic
# GOOD: each concern in its own layer
# Data access layer
class OrderRepository:
def find_by_id(self, order_id: str) -> Order: ...
def save(self, order: Order) -> None: ...
# Business logic layer (domain)
class OrderProcessor:
def __init__(self, shipping: ShippingCalculator, membership: MembershipService):
self._shipping = shipping
self._membership = membership
def process(self, order: Order) -> Order:
discount = self._membership.get_discount(order.customer_id)
shipping = self._shipping.calculate(order.subtotal, order.country)
order.apply_discount(discount)
order.set_shipping(shipping)
order.mark_processed()
return order
# Presentation layer
class OrderSerializer:
def to_html(self, order: Order) -> str:
return f"<html><body>Order {order.id}: ${order.total:.2f} processed</body></html>"
def to_json(self, order: Order) -> dict:
return {"order_id": order.id, "total": order.total, "status": order.status}
ตอนนี้จะแก้ จะ test หรือจะเปลี่ยนตัวใหม่ ก็ทำทีละ layer ได้โดยไม่ต้องยุ่งกับ layer อื่น
5. High Cohesion, Low Coupling¶
สองคำนี้คือโครงสร้างพื้นฐานของ software architecture ที่ดี
Cohesion วัดว่าหน้าที่ต่าง ๆ ใน module เดียวกันเกี่ยวข้องกันแน่นแค่ไหน high cohesion คือ module ทำเรื่องเดียว และทำเรื่องนั้นครบจบในตัว
Coupling วัดว่า module หนึ่งพึ่ง module อื่นมากแค่ไหน low coupling คือแก้ module หนึ่งแล้วกระทบ module อื่นน้อยที่สุด
THE IDEAL:
HIGH COHESION: LOW COUPLING:
Everything inside a module Modules depend on each other
is related to one concept. as little as possible.
┌────────────────┐ ┌─────┐ ┌─────┐
│ UserAccount │ │ A │ ───────→ │ B │
│ │ └─────┘ thin └─────┘
│ - authenticate │ interface
│ - changePassword│
│ - resetToken │ NOT:
│ - verifyEmail │
│ │ ┌─────┐ ┌─────┐
│ (all about │ │ A │◄────────►│ B │
│ one account) │ └─────┘ tightly └─────┘
└────────────────┘ tangled
class ที่ทำทั้ง user authentication ส่ง email สร้างรายงาน PDF แล้วยัง query database เองอีก คือ class ที่ low cohesion เพราะเหมาทำทุกอย่าง ส่วน class ที่ high cohesion ทำเรื่องเดียวและทำได้ดี
Part 2: SOLID — หลักการออกแบบ Object-Oriented 5 ข้อ¶
SOLID เป็นตัวย่อที่ Robert C. Martin ("Uncle Bob") ตั้งขึ้น ใช้เรียกหลักการ 5 ข้อที่ช่วยให้งานออกแบบแบบ object-oriented อ่านเข้าใจง่าย ยืดหยุ่น และ maintain ได้
S — Single Responsibility Principle
O — Open/Closed Principle
L — Liskov Substitution Principle
I — Interface Segregation Principle
D — Dependency Inversion Principle
S — Single Responsibility Principle (SRP)¶
"class หนึ่งควรมีเหตุผลที่ต้องแก้แค่ข้อเดียวเท่านั้น"
คำสำคัญคือ เหตุผลที่ต้องแก้ (reason to change) จะนับว่า class มี responsibility เดียว ก็ต่อเมื่อมีเหตุผลทาง business แค่แบบเดียวที่ทำให้ต้องแก้
บททดสอบ: มี "เจ้านาย" สองคนไหม¶
ถ้ามีคนสองคนในองค์กรที่มีสิทธิ์ขอให้คุณแก้ class เดียวกันได้ แปลว่า class นั้นแบก responsibility เกินหนึ่งอย่างแล้ว
# BAD: this class has THREE reasons to change
class UserReport:
def __init__(self, db):
self._db = db
def get_user_data(self, user_id: str) -> dict:
# Database team could ask to change this
return self._db.query("SELECT * FROM users WHERE id = ?", user_id)
def format_report(self, user_data: dict) -> str:
# Design/product team could ask to change this
return f"User Report\n{'='*40}\n" + "\n".join(
f"{k}: {v}" for k, v in user_data.items()
)
def send_report(self, email: str, report: str) -> None:
# Infrastructure/ops team could ask to change this
smtp = smtplib.SMTP("smtp.company.com")
smtp.sendmail("reports@company.com", email, report)
class นี้มีเจ้านายสามคน คือ DBA ที่ดูแลโครงสร้าง query ทีม product ที่กำหนดหน้าตารายงาน และทีม ops ที่ดูแลการส่ง email พอมี change request มาหนึ่งเรื่อง ก็ต้องแก้ใน class เดียวกันนี้ ซึ่งอาจลากส่วนของคนอื่นพังไปด้วย
# GOOD: one reason to change each
class UserRepository:
"""Only reason to change: how we store/retrieve users."""
def __init__(self, db):
self._db = db
def find_by_id(self, user_id: str) -> dict:
return self._db.query("SELECT * FROM users WHERE id = ?", user_id)
class UserReportFormatter:
"""Only reason to change: how the report looks."""
def format(self, user_data: dict) -> str:
return f"User Report\n{'='*40}\n" + "\n".join(
f"{k}: {v}" for k, v in user_data.items()
)
class EmailSender:
"""Only reason to change: how we send email."""
def __init__(self, smtp_host: str):
self._smtp_host = smtp_host
def send(self, to: str, subject: str, body: str) -> None:
smtp = smtplib.SMTP(self._smtp_host)
smtp.sendmail("reports@company.com", to, body)
# The orchestrator — its only job is to coordinate
class UserReportService:
def __init__(self, repo: UserRepository, formatter: UserReportFormatter,
sender: EmailSender):
self._repo = repo
self._formatter = formatter
self._sender = sender
def send_user_report(self, user_id: str, recipient_email: str) -> None:
user_data = self._repo.find_by_id(user_id)
report = self._formatter.format(user_data)
self._sender.send(recipient_email, "User Report", report)
SRP ≠ หนึ่ง class มีหนึ่ง method
SRP หมายถึงมี เหตุผลที่ต้องแก้ ข้อเดียว ไม่ใช่มี function เดียว class ShoppingCart จะมี add_item, remove_item, apply_coupon และ calculate_total ก็ได้ เพราะทั้งหมดเป็นส่วนหนึ่งของ responsibility เดียวกัน คือดูแลของในตะกร้า
O — Open/Closed Principle (OCP)¶
"software entity ควรเปิดให้ extend แต่ปิดไม่ให้แก้ไข"
พอมี requirement ใหม่ คุณควร เพิ่ม behavior ใหม่ได้ โดยไม่ต้อง แก้ โค้ดเดิมที่ทำงานได้อยู่แล้ว โค้ดเดิมผ่าน test มาแล้ว ไว้ใจได้ และรันอยู่บน production แก้ทีไรก็เสี่ยงทุกที
สัญญาณเตือน: if/elif ที่ยาวขึ้นเรื่อย ๆ¶
# BAD: adding a new shape requires modifying this function
def calculate_area(shape: dict) -> float:
if shape['type'] == 'circle':
return math.pi * shape['radius'] ** 2
elif shape['type'] == 'rectangle':
return shape['width'] * shape['height']
elif shape['type'] == 'triangle':
return 0.5 * shape['base'] * shape['height']
# Every new shape means modifying this function — opening it to bugs
elif shape['type'] == 'pentagon':
...
# GOOD: open for extension (add new shapes), closed for modification
from abc import ABC, abstractmethod
import math
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
class Circle(Shape):
def __init__(self, radius: float):
self.radius = radius
def area(self) -> float:
return math.pi * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width: float, height: float):
self.width = width
self.height = height
def area(self) -> float:
return self.width * self.height
class Triangle(Shape):
def __init__(self, base: float, height: float):
self.base = base
self.height = height
def area(self) -> float:
return 0.5 * self.base * self.height
# Adding Pentagon requires ZERO changes to existing code:
class Pentagon(Shape):
def __init__(self, side: float):
self.side = side
def area(self) -> float:
return (self.side ** 2 * math.sqrt(25 + 10 * math.sqrt(5))) / 4
def calculate_total_area(shapes: list[Shape]) -> float:
return sum(shape.area() for shape in shapes)
OCP ทำได้ด้วย polymorphism และ abstraction ออกแบบให้โค้ดพึ่ง interface หรือ abstract class แล้วคุณจะเพิ่ม implementation ใหม่ได้โดยไม่ต้องแตะโค้ดเดิมเลย
ตัวอย่าง OCP จากงานจริง: Payment Processing¶
# BAD: adding PayPal or Apple Pay means modifying PaymentProcessor
class PaymentProcessor:
def process(self, amount: float, method: str, details: dict) -> bool:
if method == "credit_card":
return self._charge_stripe(amount, details['card_token'])
elif method == "bank_transfer":
return self._initiate_ach(amount, details['account_number'])
# Adding PayPal: modify this class and risk breaking Stripe + ACH
# GOOD: each payment method is a separate, addable implementation
class PaymentGateway(ABC):
@abstractmethod
def process(self, amount: float, details: dict) -> PaymentResult: ...
class StripeGateway(PaymentGateway):
def process(self, amount: float, details: dict) -> PaymentResult:
# Stripe-specific logic
...
class ACHGateway(PaymentGateway):
def process(self, amount: float, details: dict) -> PaymentResult:
# ACH-specific logic
...
class PayPalGateway(PaymentGateway): # Added without modifying anything above
def process(self, amount: float, details: dict) -> PaymentResult:
# PayPal-specific logic
...
class PaymentProcessor:
def __init__(self, gateway: PaymentGateway): # depends on abstraction
self._gateway = gateway
def charge(self, amount: float, details: dict) -> PaymentResult:
return self._gateway.process(amount, details)
L — Liskov Substitution Principle (LSP)¶
"ต้องเอา object ของ subtype ไปใช้แทน object ของ supertype ได้ โดยโปรแกรมไม่พัง" — Barbara Liskov, 1987
ถ้า class B extends class A ทุกจุดที่ใช้ A อยู่ ต้องเอา B ไปใส่แทนได้ และโปรแกรมยังทำงานถูกต้อง ถ้าใส่ B แล้วมีอะไรพัง แปลว่าออกแบบ inheritance ผิดตั้งแต่แรก
ตัวอย่างคลาสสิกที่ผิด LSP: Square กับ Rectangle¶
# BAD: Square extends Rectangle — but violates LSP
class Rectangle:
def __init__(self, width: float, height: float):
self.width = width
self.height = height
def area(self) -> float:
return self.width * self.height
class Square(Rectangle):
def __init__(self, side: float):
super().__init__(side, side)
# "Square" must override setters to keep width == height
@Rectangle.width.setter
def width(self, value: float):
self._width = value
self._height = value # forces height to match
@Rectangle.height.setter
def height(self, value: float):
self._height = value
self._width = value # forces width to match
# This function works correctly with Rectangle
def double_width(shape: Rectangle) -> float:
shape.width *= 2
return shape.area() # expects: width * height (unchanged)
r = Rectangle(4, 5)
print(double_width(r)) # 40.0 ✅ correct
s = Square(4)
print(double_width(s)) # 64.0 ❌ expected 40.0 — LSP violated!
# Substituting Square for Rectangle broke the function
# GOOD: Square and Rectangle share an interface, not an inheritance chain
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
class Rectangle(Shape):
def __init__(self, width: float, height: float):
self._width = width
self._height = height
def area(self) -> float:
return self._width * self._height
class Square(Shape):
def __init__(self, side: float):
self._side = side
def area(self) -> float:
return self._side ** 2
ตัวอย่างนก¶
# BAD: Penguin can't fly — inheriting from Bird violates LSP
class Bird:
def fly(self) -> str:
return "I am flying!"
class Penguin(Bird):
def fly(self) -> str:
raise NotImplementedError("Penguins can't fly!") # LSP violation
def make_bird_fly(bird: Bird) -> str:
return bird.fly() # breaks when called with Penguin
# GOOD: model what birds actually have in common
class Bird(ABC):
@abstractmethod
def move(self) -> str: ...
class FlyingBird(Bird):
def move(self) -> str:
return "flying"
def fly(self) -> str:
return "I am flying!"
class SwimmingBird(Bird):
def move(self) -> str:
return "swimming"
class Eagle(FlyingBird): ...
class Duck(FlyingBird): ... # ducks can also swim — add SwimmingBird mixin
class Penguin(SwimmingBird): ...
เช็ค LSP: "Is-A" ไม่พอ ต้อง "Behaves-As"¶
บททดสอบ OOP แบบมาตรฐานคือถามว่า "Penguin เป็น Bird ไหม?" คำตอบคือใช่ inheritance เลยดูเข้าท่า แต่ LSP ต้องการบททดสอบที่เข้มกว่านั้น: "Penguin ทำตัวแบบ Bird ได้ในทุกจุดที่ใช้ Bird ไหม?" คำตอบคือไม่ได้ แปลว่า inheritance ตรงนี้ผิด
เช็คด้วย พฤติกรรม เสมอ อย่าดูแค่ในเชิงแนวคิด
I — Interface Segregation Principle (ISP)¶
"อย่าบังคับให้ client ต้องพึ่ง method ที่ตัวเองไม่ได้ใช้"
interface ที่อ้วนเกินไปบังคับให้คน implement ต้องเขียน method ที่ตัวเองไม่ได้ใช้ ส่วนใหญ่ก็ออกมาเป็น stub ว่าง ๆ หรือ raise NotImplementedError() ซึ่งก็คือการผิด LSP แบบเงียบ ๆ ที่รอวันระเบิด
ปัญหา Multi-Function Device¶
# BAD: one giant interface — not every device can do everything
class MultifunctionDevice(ABC):
@abstractmethod
def print_document(self, doc: Document) -> None: ...
@abstractmethod
def scan_document(self) -> Document: ...
@abstractmethod
def send_fax(self, doc: Document, number: str) -> None: ...
@abstractmethod
def copy_document(self, doc: Document) -> None: ...
class OldPrinter(MultifunctionDevice):
def print_document(self, doc: Document) -> None:
# actual implementation
...
def scan_document(self) -> Document:
raise NotImplementedError("This printer cannot scan") # forced stub
def send_fax(self, doc: Document, number: str) -> None:
raise NotImplementedError("This printer cannot fax") # forced stub
def copy_document(self, doc: Document) -> None:
raise NotImplementedError("This printer cannot copy") # forced stub
# GOOD: small, specific interfaces — implement only what you can do
class Printer(ABC):
@abstractmethod
def print_document(self, doc: Document) -> None: ...
class Scanner(ABC):
@abstractmethod
def scan_document(self) -> Document: ...
class Fax(ABC):
@abstractmethod
def send_fax(self, doc: Document, number: str) -> None: ...
class OldPrinter(Printer):
def print_document(self, doc: Document) -> None:
# prints
...
class ModernMFD(Printer, Scanner, Fax):
def print_document(self, doc: Document) -> None: ...
def scan_document(self) -> Document: ...
def send_fax(self, doc: Document, number: str) -> None: ...
ISP ในการออกแบบ API (Python Protocol / TypeScript Interface)¶
# Python Protocol — structural typing, no explicit inheritance needed
from typing import Protocol
class Readable(Protocol):
def read(self, n: int = -1) -> bytes: ...
class Writable(Protocol):
def write(self, data: bytes) -> int: ...
class Seekable(Protocol):
def seek(self, pos: int) -> int: ...
def tell(self) -> int: ...
# Functions depend only on what they actually need
def compress(source: Readable, dest: Writable) -> None:
# only needs read and write — not seek
...
def copy_section(source: Readable & Seekable, dest: Writable,
start: int, length: int) -> None:
# needs read AND seek
source.seek(start)
data = source.read(length)
dest.write(data)
D — Dependency Inversion Principle (DIP)¶
"module ระดับสูงไม่ควรพึ่ง module ระดับล่าง ทั้งคู่ควรพึ่ง abstraction ส่วน abstraction ไม่ควรพึ่งรายละเอียด รายละเอียดต่างหากที่ต้องพึ่ง abstraction"
ถ้ามองในระดับ architecture ข้อนี้สำคัญที่สุดใน SOLID เพราะเป็นตัวที่ทำให้ test ได้ เปลี่ยน implementation ได้ และทำให้ coupling หลวม
ทิศทางของ Dependency: แบบผิดกับแบบถูก¶
WITHOUT DIP (coupled to implementation):
OrderService ──depends on──→ PostgresDatabase
(high-level) (low-level detail)
Change PostgreSQL → Change OrderService
Test OrderService → Need PostgreSQL running
Switch to MongoDB → Rewrite OrderService
WITH DIP (coupled to abstraction):
OrderService ──depends on──→ OrderRepository (interface)
(high-level) (abstraction)
▲ ▲
│ │
└──────────────────────────────┘
PostgresOrderRepository (detail)
MongoOrderRepository (detail)
InMemoryOrderRepository (for tests)
# BAD: high-level module directly depends on low-level module
class OrderService:
def __init__(self):
# Hard dependency on specific implementation
self._db = psycopg2.connect("postgresql://localhost/orders")
self._emailer = smtplib.SMTP("smtp.sendgrid.net")
def place_order(self, cart: Cart) -> str:
# Uses _db directly — impossible to test without PostgreSQL
cursor = self._db.cursor()
cursor.execute("INSERT INTO orders ...")
order_id = cursor.fetchone()[0]
self._emailer.sendmail(...)
return order_id
# GOOD: both high-level and low-level depend on abstractions
from abc import ABC, abstractmethod
# Abstractions (the boundary)
class OrderRepository(ABC):
@abstractmethod
def save(self, order: Order) -> str: ...
class EmailService(ABC):
@abstractmethod
def send_confirmation(self, order: Order, recipient: str) -> None: ...
# High-level module — depends only on abstractions
class OrderService:
def __init__(self, order_repo: OrderRepository, email_service: EmailService):
self._orders = order_repo
self._email = email_service
def place_order(self, cart: Cart, customer_email: str) -> str:
order = Order.from_cart(cart)
order_id = self._orders.save(order)
self._email.send_confirmation(order, customer_email)
return order_id
# Low-level implementations — depend on abstractions too
class PostgresOrderRepository(OrderRepository):
def __init__(self, connection_string: str):
self._conn = psycopg2.connect(connection_string)
def save(self, order: Order) -> str:
# PostgreSQL-specific implementation
...
class SendGridEmailService(EmailService):
def send_confirmation(self, order: Order, recipient: str) -> None:
# SendGrid-specific implementation
...
# For tests — no real database or email needed:
class InMemoryOrderRepository(OrderRepository):
def __init__(self):
self._store: dict[str, Order] = {}
def save(self, order: Order) -> str:
self._store[order.id] = order
return order.id
class FakeEmailService(EmailService):
def __init__(self):
self.sent_confirmations: list[tuple[Order, str]] = []
def send_confirmation(self, order: Order, recipient: str) -> None:
self.sent_confirmations.append((order, recipient))
# Tests are now fast, isolated, and reliable
def test_place_order_sends_confirmation_email():
repo = InMemoryOrderRepository()
email = FakeEmailService()
service = OrderService(repo, email)
cart = Cart.with_items([CartItem("Book A", 29.99)])
order_id = service.place_order(cart, "customer@example.com")
assert order_id is not None
assert len(email.sent_confirmations) == 1
assert email.sent_confirmations[0][1] == "customer@example.com"
Part 3: หลักการขั้นสูง (Advanced Principles)¶
Law of Demeter — คุยกับเพื่อนใกล้ตัวเท่านั้น¶
"คุยแค่กับเพื่อนที่อยู่ใกล้ตัว"
Law of Demeter มีอีกชื่อว่า Principle of Least Knowledge บอกว่า method หนึ่งควรเรียก method ได้แค่จาก: 1. ตัวเอง 2. field ของตัวเอง 3. object ที่ส่งเข้ามาเป็น parameter 4. object ที่สร้างขึ้นเองภายใน method
แต่ ไม่ควร ล้วงทะลุ object ตัวกลาง เข้าไปเรียก method ข้างในต่ออีกทอด
# BAD: violates Law of Demeter — "train wreck" chaining
class OrderService:
def notify_customer(self, order: Order) -> None:
# Reaching through order → customer → contact_info → email
# OrderService now depends on: Order, Customer, ContactInfo, Email
email = order.get_customer().get_contact_info().get_primary_email().get_address()
self._email_client.send(email, "Your order is ready")
# GOOD: tell Order to handle the notification, or pass email directly
class Order:
def get_customer_email(self) -> str:
return self._customer.primary_email # encapsulated internally
class OrderService:
def notify_customer(self, order: Order) -> None:
email = order.get_customer_email() # one level deep
self._email_client.send(email, "Your order is ready")
chain ยาวแบบ "train wreck" (a.b().c().d()) คือสัญญาณว่าผิด Law of Demeter โค้ดของคุณจะผูกติดกับ object ทุกตัวใน chain ตัวไหนเปลี่ยน คุณก็พังตาม
Composition over Inheritance¶
"เลือก object composition ก่อน class inheritance" — Gang of Four, Design Patterns
inheritance ให้ hierarchy ที่แข็งทื่อและเปราะ ส่วน composition ให้ behavior ที่ยืดหยุ่น เปลี่ยนได้ง่าย
# BAD: inheritance hierarchy that gets tangled fast
class Animal:
def breathe(self): ...
class Pet(Animal):
def be_trained(self): ...
class Dog(Pet):
def bark(self): ...
class RobotDog(???): # Robot dogs don't breathe — now what?
# Can't extend Animal without getting breathe()
def bark(self): ...
# GOOD: compose behaviors from smaller pieces
class Barker:
def bark(self) -> str:
return "Woof!"
class Trainer:
def train(self, command: str) -> str:
return f"Learning: {command}"
class Breather:
def breathe(self) -> str:
return "Inhale... exhale..."
class Dog:
def __init__(self):
self._barker = Barker()
self._trainer = Trainer()
self._breather = Breather()
def bark(self) -> str: return self._barker.bark()
def train(self, cmd: str) -> str: return self._trainer.train(cmd)
def breathe(self) -> str: return self._breather.breathe()
class RobotDog:
def __init__(self):
self._barker = Barker() # shares Barker behavior
self._trainer = Trainer() # shares training behavior
# No Breather — robots don't breathe. No problem.
def bark(self) -> str: return self._barker.bark()
def train(self, cmd: str) -> str: return self._trainer.train(cmd)
composition ให้คุณกำหนดได้ละเอียดว่า object มี behavior อะไรบ้าง หยิบเฉพาะที่ต้องใช้ ส่วน inheritance บังคับให้รับทุกอย่างที่ parent chain มีมาด้วย
เมื่อไหร่ที่ Inheritance เป็นตัวเลือกที่ใช่¶
ใช้ inheritance เมื่อ: - มีความสัมพันธ์แบบ is-a จริง ๆ ที่นิ่งแล้วและไม่น่าจะเปลี่ยน - อยากแชร์ default implementation ให้ type กลุ่มเดียวกันใช้ร่วมกัน - ตั้งใจใช้ template method pattern
inheritance เหมาะกับ framework hook และ taxonomy ที่นิ่งแล้วมากที่สุด ถ้าเป็น domain behavior ที่ต้องยืดหยุ่น เลือก composition ดีกว่า
Command Query Separation (CQS)¶
"ทุก method ต้องเป็นอย่างใดอย่างหนึ่ง จะเป็น Command (เปลี่ยน state) หรือ Query (คืนข้อมูล) ก็ได้ แต่ห้ามเป็นทั้งสองอย่าง" — Bertrand Meyer
CQS ทำให้อ่านโค้ดแล้วเดาพฤติกรรมได้ง่ายขึ้นเยอะ เรียก query เมื่อไหร่ก็ปลอดภัย (ไม่มี side effect) ส่วน command เปลี่ยน state แต่ไม่คืนค่าอะไรกลับมา
# BAD: method both changes state AND returns data
class ShoppingCart:
def remove_item_and_get_total(self, item_id: str) -> float:
self._items = [i for i in self._items if i.id != item_id]
return sum(i.price for i in self._items) # mutation + query mixed
# BAD: "is_valid" sounds like a query but has side effects
class Form:
def is_valid(self) -> bool:
result = self._validate()
self._save_validation_errors() # hidden side effect!
self._send_validation_event() # caller is surprised
return result
# GOOD: separate commands from queries
class ShoppingCart:
def remove_item(self, item_id: str) -> None: # Command: changes state
self._items = [i for i in self._items if i.id != item_id]
def total(self) -> float: # Query: reads state
return sum(i.price for i in self._items)
class Form:
def validate(self) -> None: # Command: runs validation
self._errors = self._run_validation()
def is_valid(self) -> bool: # Query: reads errors
return len(self._errors) == 0
def errors(self) -> list[str]: # Query: reads errors
return list(self._errors)
ข้อดีคือ developer เห็น cart.total() ก็รู้แน่ ๆ ว่าไม่มีอะไรเปลี่ยน เห็น cart.remove_item() ก็รู้ว่า state เปลี่ยน ไม่มีเซอร์ไพรส์
Tell, Don't Ask¶
"บอก object ว่าให้ทำอะไร อย่าไปขอข้อมูลจาก object มาแล้วตัดสินใจเอง"
หลักการนี้คือการวาง behavior ไว้ที่เดียวกับข้อมูล ถ้าคุณดึง state ของ object ออกมาแค่เพื่อตัดสินใจเรื่องที่ object ควรตัดสินใจเองได้ แปลว่าคุณกำลังทำลาย encapsulation
# BAD: asking for data, making the decision externally
class OrderProcessor:
def apply_discount(self, customer: Customer, order: Order) -> None:
# Asking customer for its data, making the decision here
if customer.membership_tier == "gold":
if customer.total_purchases > 1000:
order.discount = 0.20
else:
order.discount = 0.10
elif customer.membership_tier == "silver":
order.discount = 0.05
# GOOD: tell the customer to determine its own discount
class Customer:
def applicable_discount(self) -> float:
if self.membership_tier == "gold":
return 0.20 if self.total_purchases > 1000 else 0.10
if self.membership_tier == "silver":
return 0.05
return 0.0
class OrderProcessor:
def apply_discount(self, customer: Customer, order: Order) -> None:
order.apply_discount(customer.applicable_discount()) # tell, don't ask
ตอนนี้ logic ส่วนลดอยู่ในที่ที่ควรอยู่ คือใน class Customer ติดกับข้อมูลที่ใช้คำนวณ กฎส่วนลดเปลี่ยนเมื่อไหร่ ก็แก้ที่เดียวจบ
Fail Fast¶
"เกิด error เมื่อไหร่ ให้รายงานออกมาเร็วที่สุดเท่าที่ทำได้"
Fail Fast บอกว่า validate input ให้เร็วที่สุด เจออะไรผิดก็ raise error ทันที อย่าปล่อยให้ state ผิด ๆ ไหลลึกเข้าไปในระบบ จน error ไปโผล่ไกลจากต้นเหตุ
# BAD: fails late — error is thrown deep in the call stack
def process_payment(amount, currency, user_id):
# No validation here...
payment = Payment(amount=amount, currency=currency)
user = UserService.get(user_id) # fails here if user_id is None
# If we got here with amount=-100, we'll find out later in billing
PaymentGateway.charge(user.payment_method, payment)
# GOOD: fails fast — errors caught at the entry point
def process_payment(amount: float, currency: str, user_id: str) -> None:
# Validate at the boundary before doing anything
if amount <= 0:
raise ValueError(f"Payment amount must be positive, got: {amount}")
if len(currency) != 3:
raise ValueError(f"Currency must be ISO 3-letter code, got: {currency}")
if not user_id:
raise ValueError("user_id is required")
payment = Payment(amount=amount, currency=currency)
user = UserService.get(user_id)
PaymentGateway.charge(user.payment_method, payment)
Fail Fast สำคัญเป็นพิเศษใน constructor และ value object ต้องไม่มีทางสร้าง object ที่ state ผิดขึ้นมาได้เลย:
@dataclass(frozen=True)
class Money:
amount: Decimal
currency: str
def __post_init__(self):
# Fail fast in the constructor — no invalid Money objects can exist
if self.amount < 0:
raise ValueError(f"Money amount cannot be negative: {self.amount}")
if len(self.currency) != 3:
raise ValueError(f"Currency must be 3-letter ISO code: {self.currency}")
The Boy Scout Rule¶
"ทิ้งที่ตั้งแคมป์ไว้ให้สะอาดกว่าตอนที่มาถึงเสมอ" — Robert C. Martin
แตะโค้ดตรงไหน ก็ทิ้งไว้ให้ดีกว่าเดิมอีกนิด เปลี่ยนชื่อตัวแปรที่อ่านแล้วงง แตก function 50 บรรทัดออกมา เพิ่ม test ที่ขาดไป
Boy Scout Rule คือคำตอบที่ใช้ได้จริงของคำถาม "codebase รก ๆ จะทำให้ดีขึ้นยังไง ถ้าไม่ rewrite ครั้งใหญ่?" คำตอบคือไม่ต้อง rewrite แต่ค่อย ๆ เก็บกวาดไประหว่างทำงาน
# You're adding a new feature to calculate_invoice()
# You notice: confusing variable names, magic numbers, no tests
# BEFORE (what you found)
def calculate_invoice(c, items, d=False):
t = 0
for i in items:
t += i[0] * i[1]
if d:
t = t * 0.85
if t > 500:
t = t - 25
return t
# AFTER (what you leave — naming, constants, clarity)
BULK_ORDER_THRESHOLD = 500.00
BULK_ORDER_DISCOUNT = 25.00
MEMBER_DISCOUNT_RATE = 0.15
def calculate_invoice(
customer_id: str,
line_items: list[tuple[float, int]], # (unit_price, quantity)
is_member: bool = False
) -> float:
subtotal = sum(unit_price * quantity for unit_price, quantity in line_items)
if is_member:
subtotal *= (1 - MEMBER_DISCOUNT_RATE)
if subtotal > BULK_ORDER_THRESHOLD:
subtotal -= BULK_ORDER_DISCOUNT
return subtotal
ไม่ได้ rewrite อะไรเลย แค่เก็บแคมป์ให้สะอาดขึ้น ทำแบบนี้ทุกครั้งที่แตะโค้ด แล้ว codebase ที่รกจะค่อย ๆ กลับมาจัดการได้
Part 4: หลักการสำหรับ Cloud-Native และ Distributed System¶
หลักการออกแบบสายคลาสสิกเขียนขึ้นมาสำหรับระบบ single-process ที่ทุกอย่างอยู่ใน memory แต่ cloud-native architecture มี failure mode ใหม่ ๆ เพิ่มเข้ามา ทั้ง network partition, partial failure และ eventual consistency เรื่องพวกนี้ต้องมีหลักการเฉพาะของตัวเอง
Design for Failure¶
"ทุกอย่างพังได้ และพังอยู่ตลอดเวลา" — Werner Vogels, CTO ของ Amazon
ใน distributed system network call ไหนก็ fail ได้ service ไหนก็ช้าได้ dependency ไหนก็ล่มได้ ต้องออกแบบรับเรื่องนี้ไว้ตั้งแต่วันแรก
# BAD: assumes the external service always responds
class ProductService:
def get_price(self, product_id: str) -> float:
response = requests.get(f"{CATALOG_URL}/products/{product_id}")
return response.json()['price'] # what if this times out? what if catalog is down?
# GOOD: circuit breaker + fallback + timeout
import tenacity
from circuitbreaker import circuit
class ProductService:
def __init__(self, catalog_client: CatalogClient, cache: Cache):
self._catalog = catalog_client
self._cache = cache
@circuit(failure_threshold=5, recovery_timeout=30)
@tenacity.retry(
stop=tenacity.stop_after_attempt(3),
wait=tenacity.wait_exponential(min=1, max=8),
retry=tenacity.retry_if_exception_type(RequestException),
)
def get_price(self, product_id: str) -> float:
try:
price = self._catalog.get_price(product_id)
self._cache.set(f"price:{product_id}", price, ttl=300)
return price
except (RequestException, Timeout):
# Fallback: serve cached value if catalog is unavailable
cached = self._cache.get(f"price:{product_id}")
if cached is not None:
return cached
raise # propagate if no fallback available
Design for Observability¶
service ที่ observe ไม่ได้ก็คือกล่องดำ พอพังตอนตีสาม คุณต้องรู้ให้ได้ว่า อะไร พัง เพราะอะไร และ เมื่อไหร่
ใส่ความสามารถ 3 อย่างนี้ไว้ตั้งแต่วันแรก:
# Logs + Metrics + Traces — the observability triad
import structlog
from opentelemetry import trace, metrics
import time
log = structlog.get_logger()
tracer = trace.get_tracer("order-service")
meter = metrics.get_meter("order-service")
# Metrics
orders_placed = meter.create_counter("orders.placed.total")
order_duration = meter.create_histogram("orders.duration.ms")
order_errors = meter.create_counter("orders.errors.total")
def place_order(cart_id: str, customer_id: str) -> str:
start = time.time()
with tracer.start_as_current_span("place_order") as span:
span.set_attribute("cart.id", cart_id)
span.set_attribute("customer.id", customer_id)
log.info("placing_order", cart_id=cart_id, customer_id=customer_id)
try:
order = _do_place_order(cart_id, customer_id)
orders_placed.add(1, {"status": "success"})
log.info("order_placed", order_id=order.id, total=str(order.total))
span.set_attribute("order.id", order.id)
return order.id
except Exception as e:
order_errors.add(1, {"error_type": type(e).__name__})
log.error("order_failed", cart_id=cart_id, error=str(e))
span.record_exception(e)
raise
finally:
duration_ms = (time.time() - start) * 1000
order_duration.record(duration_ms)
log.info("order_duration", duration_ms=duration_ms)
Idempotency — retry ซ้ำได้โดยไม่พัง¶
ใน distributed system พอ operation ไหน fail ระบบก็ retry เป็นเรื่องปกติ operation ที่ idempotent จะให้ผลลัพธ์เหมือนเดิมเสมอ ไม่ว่าจะรันครั้งเดียวหรือสิบครั้ง
# BAD: double-processing an order charges the customer twice
class OrderProcessor:
def process_payment(self, order_id: str, amount: float) -> None:
stripe.Charge.create(amount=int(amount * 100), currency="usd")
# If this method is called twice (retry after network error),
# customer is charged twice. 😱
# GOOD: idempotency key prevents double-charging
class OrderProcessor:
def process_payment(self, order_id: str, amount: float) -> str:
# order_id as idempotency key: same order_id = same charge
# Stripe deduplicates on the idempotency key
charge = stripe.Charge.create(
amount=int(amount * 100),
currency="usd",
idempotency_key=f"order-payment-{order_id}", # safe to retry
)
return charge.id
# Database upsert as idempotency pattern
def upsert_inventory_reservation(order_id: str, product_id: str, qty: int) -> None:
db.execute("""
INSERT INTO inventory_reservations (order_id, product_id, quantity)
VALUES (:order_id, :product_id, :qty)
ON CONFLICT (order_id, product_id)
DO UPDATE SET quantity = :qty, updated_at = NOW()
""", {"order_id": order_id, "product_id": product_id, "qty": qty})
# Safe to call multiple times — same result every time
Stateless Services¶
stateless service ไม่เก็บ session state ไว้ใน memory ข้าม request request ไหนจะไปลง instance ไหนก็ได้ และนี่แหละคือสิ่งที่ทำให้ scale แบบ horizontal ได้
# BAD: server-side session state — sticky sessions required
class OrderService:
_user_sessions: dict = {} # In-memory state — dies on restart
def start_checkout(self, user_id: str, cart: dict) -> str:
session_id = str(uuid4())
self._user_sessions[session_id] = cart # stored in THIS instance only
return session_id
def complete_checkout(self, session_id: str) -> None:
cart = self._user_sessions.get(session_id) # only works on same instance
if not cart:
raise SessionNotFoundError(session_id)
# GOOD: externalized state — any instance can serve any request
class OrderService:
def __init__(self, session_store: Redis):
self._sessions = session_store
def start_checkout(self, user_id: str, cart: dict) -> str:
session_id = str(uuid4())
self._sessions.setex(
f"checkout:{session_id}",
3600,
json.dumps(cart)
) # stored in Redis — any pod can read it
return session_id
def complete_checkout(self, session_id: str) -> None:
data = self._sessions.get(f"checkout:{session_id}")
if not data:
raise SessionNotFoundError(session_id)
cart = json.loads(data)
# ... process order from cart
รวมทุกข้อเข้าด้วยกัน: แผนที่หลักการ¶
หลักการพวกนี้ไม่ได้อยู่แยกกันโดด ๆ แต่เสริมกันและกัน ดูความเชื่อมโยงได้จากแผนภาพนี้:
FOUNDATIONAL
┌─────────────────────────────────────────────────────────────┐
│ KISS → enables → DRY → enables → SoC → enables → Cohesion │
│ YAGNI + Coupling │
└─────────────────────────────────────────────────────────────┘
↓ builds on
SOLID
┌─────────────────────────────────────────────────────────────┐
│ SRP (clear responsibility) │
│ OCP (stable abstractions) ←── DIP (depend on abstractions│
│ LSP (correct inheritance) │
│ ISP (lean interfaces) │
└─────────────────────────────────────────────────────────────┘
↓ refined by
ADVANCED
┌─────────────────────────────────────────────────────────────┐
│ LoD (minimize knowledge) CQS (clear intent) │
│ Composition (flexibility) Tell Don't Ask (encapsulation) │
│ Fail Fast (early errors) Boy Scout (continuous care) │
└─────────────────────────────────────────────────────────────┘
↓ extended for
CLOUD-NATIVE
┌─────────────────────────────────────────────────────────────┐
│ Design for Failure Idempotency │
│ Design for Observability Stateless Services │
└─────────────────────────────────────────────────────────────┘
Quick Reference — สรุปทุกหลักการในหน้าเดียว¶
| หลักการ | สรุปสั้น ๆ | code smell ที่แก้ได้ |
|---|---|---|
| KISS | วิธีที่ง่ายที่สุดที่ใช้งานได้ | over-engineering, ทำ abstraction ทั้งที่ไม่จำเป็น |
| DRY | ความรู้แต่ละเรื่องมีที่อยู่หลักที่เดียว | โค้ด copy-paste, logic กระจายหลายที่ |
| YAGNI | ทำให้พอสำหรับวันนี้ ไม่ใช่เผื่อพรุ่งนี้ที่ยังมาไม่ถึง | ฟีเจอร์ที่ไม่มีใครใช้, speculative generality |
| SoC | concern ต่างกัน อยู่คนละที่ | god class, layer พันกันเป็น spaghetti |
| High Cohesion | ทุกอย่างใน module เป็นเรื่องเดียวกัน | class ที่ทำหลายเรื่องไม่เกี่ยวกัน |
| Low Coupling | module พึ่งกันให้น้อยที่สุด | ripple effect — แก้จุดเดียวพังทั้งระบบ |
| SRP | มีเหตุผลที่ต้องแก้แค่ข้อเดียว | class ที่มีเจ้านายหลายคน |
| OCP | extend ได้โดยไม่ต้องแก้โค้ดเดิม | if/elif ที่ยาวขึ้นเรื่อย ๆ |
| LSP | subtype ทำตัวแบบ parent ได้ | raise NotImplementedError ใน subclass |
| ISP | interface เล็กกระชับ ไม่ต้องเขียน stub | interface อ้วนที่มี method ไม่ได้ใช้ |
| DIP | พึ่ง abstraction ไม่ใช่ implementation | โค้ดที่ test ไม่ได้, ผูกติดกับ vendor |
| Law of Demeter | คุยกับเพื่อนใกล้ตัวเท่านั้น | method chain แบบ train wreck |
| Composition | ประกอบ behavior แทนการ inherit | inheritance hierarchy ลึกหลายชั้น |
| CQS | command เปลี่ยน state, query คืนข้อมูล | method ที่ทำทั้งสองอย่าง |
| Tell, Don't Ask | บอก object ให้ทำ อย่าไปซักไซ้เอาข้อมูล | feature envy — logic อยู่ห่างจากข้อมูลที่ใช้ |
| Fail Fast | validate ให้เร็ว พังให้เห็นชัด | error โผล่ไกลจากต้นเหตุ |
| Boy Scout Rule | ทิ้งโค้ดไว้ให้สะอาดกว่าตอนที่เจอ | legacy code ที่รกไม่มีวันจบ |
| Design for Failure | คิดไว้เลยว่าทุกอย่างพังได้ แล้วเตรียมรับมือ | timeout ที่ไม่มีใครจัดการ, cascading failure |
| Observability | log + metric + trace ตั้งแต่วันแรก | "ไม่มีใครรู้เลยว่าเกิดอะไรขึ้น" |
| Idempotency | เรียกครั้งเดียวหรือสิบครั้ง ผลก็เหมือนกัน | ตัดเงินซ้ำ, record ซ้ำ |
| Stateless | ไม่เก็บ state ใน memory ข้าม request | ต้องพึ่ง sticky session, scale ไม่ได้ |
เอาหลักการไปใช้จริงยังไง¶
ถ้าใช้ไม่เป็น หลักการพวกนี้จะกลายเป็น checklist ที่ทำให้ขยับตัวไม่ได้ แทนที่จะช่วยนำทาง ใช้ให้ได้ประโยชน์แบบนี้:
ตอนออกแบบ (ก่อนเขียนโค้ด)¶
ถามตัวเองว่า: - component นี้มี single responsibility คืออะไร? - อะไรบ้างที่จะ เปลี่ยน แยกกันได้? แยกพวกนั้นออกจากกัน - พึ่ง abstraction อะไรอยู่บ้าง? test ได้ไหมโดยไม่ต้องใช้ implementation จริง? - สิ่งที่กำลังสร้าง ต้องใช้จริง วันนี้หรือเปล่า?
ตอน Code Review¶
สิ่งที่ต้องมองหา: - method ที่ ยาวเกินไป → น่าจะผิด SRP หรือ SoC - if/elif ที่ยาวขึ้นทุกครั้งที่มี type ใหม่ → น่าจะผิด OCP - constructor ที่รับ parameter เยอะ → น่าจะผิด SRP หรือ DIP - สร้าง instance ของ external service ตรง ๆ ในโค้ด → น่าจะผิด DIP - method ที่ทั้งเปลี่ยน state และคืนข้อมูล → ผิด CQS - method chain ยาว ๆ (a.b().c().d()) → ผิด Law of Demeter
ตอน Refactor¶
ใช้ Boy Scout Rule: แตะครั้งหนึ่ง ปรับให้ดีขึ้นหนึ่งอย่าง ไม่ต้อง refactor ทั้ง class เพื่อให้ได้ SRP แค่แยก method ออกมาหนึ่งตัว เปลี่ยนชื่อตัวแปรหนึ่งตัว หรือเพิ่ม test หนึ่งตัว แล้ว codebase จะดีขึ้นไปเรื่อย ๆ
เมื่อหลักการขัดกันเอง¶
บางทีหลักการก็ชี้ไปคนละทาง ตัดสินแบบนี้:
- KISS vs OCP: requirement นิ่งแล้ว KISS ชนะ ถ้ารู้อยู่แล้วว่าต้อง extend แน่ OCP ชนะ
- DRY vs SoC: อย่ารวบสอง concern เข้าด้วยกันแค่เพราะหน้าตาคล้ายกัน ให้ SoC มาก่อนการไล่ลบโค้ดซ้ำ
- YAGNI vs DIP: ใช้ DIP เสมอ เพราะ testability ไม่ใช่เรื่องที่เดาเอา แต่ก็อย่าเพิ่ม abstraction layer ที่ยังไม่ต้องใช้
หลักการเป็น heuristic ไม่ใช่กฎตายตัว เป้าหมายจริงคือ โค้ดที่อ่านชัด ทำงานถูกต้อง test ได้ และรับการเปลี่ยนแปลงได้ หลักการเป็นแค่เครื่องมือที่พาไปถึงเป้าหมายนั้น ไม่ใช่เป้าหมายในตัวเอง
Summary¶
| หลักการ | กฎข้อเดียว | สัญญาณอันตราย |
|---|---|---|
| KISS | เลือกวิธีที่ง่ายกว่า | class ที่ต้องใช้ 10 นาทีกว่าจะอธิบายจบ |
| DRY | ความรู้แต่ละเรื่องมีที่อยู่หลักที่เดียว | logic เดียวกัน copy-paste ไว้สามที่ |
| YAGNI | อย่าสร้างของที่วันนี้ยังไม่ได้ใช้ | abstraction ที่ยังไม่มีใครเรียก |
| SRP | มีเหตุผลที่ต้องแก้แค่ข้อเดียว | constructor ที่รับ parameter ตั้งแต่ 6 ตัวขึ้นไป |
| OCP | extend ได้โดยไม่ต้องแก้โค้ดเดิม | if/elif ที่ยาวขึ้นทุกครั้งที่มี type ใหม่ |
| LSP | subtype ทำตัวแบบ parent ได้ | raise NotImplementedError ใน method ของ subclass |
| ISP | interface เล็กกระชับ ไม่ต้องเขียน stub | interface ที่มี method ซึ่ง implementor แค่ครึ่งเดียวใช้จริง |
| DIP | พึ่ง abstraction ไม่ใช่ implementation | UserService import psycopg2 ตรง ๆ |
| Law of Demeter | คุยกับเพื่อนใกล้ตัวเท่านั้น | a.getB().getC().doThing() |
| Composition | ประกอบ behavior แทนการ inherit | inheritance ลึก 5 ชั้น |
| CQS | command เปลี่ยน state, query คืนข้อมูล | method ที่ save ลง DB แล้วคืน row ที่เพิ่ง save กลับมา |
| Fail Fast | validate ที่ขอบระบบ และพังให้เห็นชัด | null check ที่ซ่อนอยู่ลึก 10 call |
| Design for Failure | คิดไว้เลยว่าทุกอย่างพังได้ | HTTP call ที่ไม่ตั้ง timeout |
| Idempotency | เรียกครั้งเดียวหรือสิบครั้ง ผลก็เหมือนกัน | การตัดเงินที่ยิงซ้ำตอน retry |
ถ้าไม่แน่ใจ ให้เริ่มจาก SRP ก่อน เพราะการตัดสินใจออกแบบดี ๆ แทบทุกอย่างที่ตามมา ล้วนต่อยอดจากข้อนี้
ถ้าอยากเจาะลึกหลักการเหล่านี้ หนังสือที่ดีที่สุดคือ Clean Code และ Clean Architecture ของ Robert C. Martin, The Pragmatic Programmer ของ Hunt & Thomas และ A Philosophy of Software Design ของ John Ousterhout สี่เล่มนี้จะเปลี่ยนวิธีคิดเรื่องโค้ดของคุณไปตลอด
มีคำถามหรืออยากคุยต่อ ทักมาได้ที่ LinkedIn, X หรือส่ง email มาได้เลย
Discussion
Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.