ข้ามไปที่เนื้อหา

Hexagonal vs Clean Architecture: โครงสร้าง โค้ด และจุดที่คนส่วนใหญ่ทำพลาด

บทความก็อ่านมาแล้ว diagram ก็เห็นมาหมดแล้ว ทั้งวงกลมซ้อนกัน หกเหลี่ยม กล่องกับลูกศรเต็มไปหมด ทฤษฎีก็เข้าใจ แต่พอเปิด IDE โปรเจกต์เปล่าขึ้นมา นั่งมองโครงสร้าง folder แล้วคิดไม่ออกว่า UserService ควรไปอยู่ตรงไหน สุดท้ายก็ได้แต่เดาเอา

Hexagonal Architecture กับ Clean Architecture สัญญาเหมือนกันว่าจะได้โค้ดที่ test ง่าย ดูแลง่าย และไม่ผูกกับ framework และทั้งคู่ก็ทำได้จริง ที่ต่างกันคืออุปมา คำศัพท์ และวิธีจัด folder แถม community ยังใช้สองคำนี้ปนกันไปหมด เลยยิ่งงงเข้าไปอีก


Part 1: DNA ที่มีร่วมกัน

ก่อนจะดูว่าต่างกันยังไง มาดูก่อนว่าเหมือนกันตรงไหน ทั้งสองแบบต่อยอดมาจากหลักการข้อเดียวกัน:

The Dependency Rule: dependency ใน source code ต้องชี้เข้าด้านใน ไปหา policy ระดับสูงกว่าเสมอ layer ด้านในห้ามรู้อะไรเกี่ยวกับ layer ด้านนอกเลย

พูดง่ายๆ คือ business logic ห้าม import database driver, HTTP framework หรือ email library เด็ดขาด ไม่มีข้อยกเว้น

WRONG (the default way everyone starts):
  UserService → imports → SQLAlchemy model
  UserService → imports → FastAPI Request
  UserService → imports → SendGrid client

RIGHT (both architectures enforce this):
  UserService → imports → UserRepository interface (abstract)
  SQLAlchemy model → implements → UserRepository interface
  FastAPI handler → calls → UserService

The arrow flips. Infrastructure depends on business logic,
not the other way around.

ทั้งสองแบบกลับทิศ dependency แบบนี้ได้เหมือนกัน ต่างกันแค่ตั้งชื่อ layer และวาดภาพคนละแบบ


Part 2: Clean Architecture — วงแหวนสี่วง

Robert C. Martin (Uncle Bob) ออกหนังสือ Clean Architecture ในปี 2017 ภาพที่ใช้อธิบายคือ วงกลมซ้อนกันสี่วง แต่ละวงคือหนึ่ง layer และ dependency rule เข้มงวดมาก วงนอกพึ่งวงในได้ แต่วงในห้ามพึ่งวงนอก

        ┌────────────────────────────────┐
        │  Presentation (Frameworks/UI)  │  ← outermost: FastAPI, Django, CLI
        │  ┌──────────────────────────┐  │
        │  │  Infrastructure          │  │  ← DB, external APIs, email, storage
        │  │  ┌────────────────────┐  │  │
        │  │  │  Application       │  │  │  ← use cases, orchestration
        │  │  │  ┌──────────────┐  │  │  │
        │  │  │  │   Domain     │  │  │  │  ← entities, business rules, events
        │  │  │  └──────────────┘  │  │  │
        │  │  └────────────────────┘  │  │
        │  └──────────────────────────┘  │
        └────────────────────────────────┘

Dependencies: Presentation → Infrastructure → Application → Domain
Domain knows nothing about anyone else.

สี่ Layer ทีละชั้น

Domain — วงในสุด เป็น business logic ล้วนๆ ไม่ import library ภายนอกเลย อย่างมากก็ใช้แค่ Python standard library - Entity (object ที่มี identity และ lifecycle) - Value Object (object ที่แยกกันด้วยค่า attribute อย่างเดียว) - Domain Event (เหตุการณ์ที่เกิดขึ้นไปแล้ว) - Business rule และ invariant

Application — สั่งงาน domain object ให้ทำตาม use case และประกาศ interface (abstract class / protocol) ไว้สำหรับของที่ต้องใช้แต่ไม่ได้ implement เอง - Use case / command handler / query handler - Abstract repository interface - Abstract service interface (email sender, payment processor)

Infrastructure — ที่อยู่ของ implementation จริง ตาม interface ที่ Application ประกาศไว้ - Repository ที่ implement ด้วย SQLAlchemy - Client สำหรับเรียก API ภายนอก - Email sender - JWT token provider

Presentation — ทางเข้าของระบบ รับ input จากข้างนอก เรียก use case ใน Application แล้วจัดรูปแบบ output ส่งกลับ - Route handler ของ FastAPI / Django - CLI command - GraphQL resolver - gRPC handler

โครงสร้างโปรเจกต์แบบ Clean Architecture

โครงสร้างนี้อิงจาก layout ของ Milan Jovanović ที่คนใช้กันเยอะ (ตามภาพ) ผมแปลงมาเป็น Python ให้แล้ว:

my_app/
│
├── domain/                          # Ring 1: Innermost
│   ├── todos/
│   │   ├── todo_item.py             # Entity
│   │   ├── priority.py              # Value Object
│   │   ├── todo_errors.py           # Domain errors
│   │   ├── todo_created_event.py    # Domain Event
│   │   ├── todo_completed_event.py  # Domain Event
│   │   └── todo_deleted_event.py    # Domain Event
│   └── users/
│       ├── user.py                  # Entity
│       ├── user_errors.py
│       └── user_registered_event.py
│
├── application/                     # Ring 2
│   ├── abstractions/
│   │   ├── repositories.py          # Abstract interfaces (Protocols)
│   │   ├── messaging.py             # Abstract event bus
│   │   └── authentication.py       # Abstract auth interface
│   ├── behaviors/
│   │   ├── logging_decorator.py     # Cross-cutting concern
│   │   └── validation_decorator.py  # Cross-cutting concern
│   ├── todos/
│   │   ├── create_todo.py           # Use case
│   │   ├── complete_todo.py         # Use case
│   │   ├── delete_todo.py           # Use case
│   │   ├── get_todos.py             # Query
│   │   └── get_todo_by_id.py        # Query
│   └── users/
│       ├── register_user.py         # Use case
│       ├── login_user.py            # Use case
│       ├── get_user_by_id.py        # Query
│       └── get_user_by_email.py     # Query
│
├── infrastructure/                  # Ring 3
│   ├── database/
│   │   ├── db_context.py            # SQLAlchemy session factory
│   │   ├── migrations/
│   │   ├── todos/
│   │   │   └── todo_configuration.py # ORM mapping
│   │   └── users/
│   │       └── user_configuration.py
│   ├── authentication/
│   │   ├── token_provider.py        # JWT implementation
│   │   ├── password_hasher.py       # bcrypt implementation
│   │   └── user_context.py          # current user from JWT
│   ├── authorization/
│   │   └── permission_handler.py
│   └── domain_events/
│       └── domain_events_dispatcher.py
│
└── presentation/                    # Ring 4: Outermost
    ├── api/
    │   ├── endpoints/
    │   │   ├── todos.py             # FastAPI router
    │   │   └── users.py             # FastAPI router
    │   └── middleware/
    │       └── error_handler.py
    ├── dependency_injection.py      # Wires everything together
    └── main.py                      # Application entry point

Part 3: Hexagonal Architecture — Ports and Adapters

Alistair Cockburn คิด Hexagonal Architecture ขึ้นในปี 2005 เร็วกว่า Clean Architecture สิบกว่าปี ภาพที่ใช้คือ หกเหลี่ยม จริงๆ รูปทรงไม่ได้มีความหมายอะไร Cockburn แค่เลือกรูปที่มีด้านพอจะวาด adapter ได้หลายตัว ชื่อทางการของแนวคิดนี้คือ Ports and Adapters

วิธีคิดต่างจากวงแหวนของ Clean Architecture พอสมควร:

              ┌──────────────────────────────────────────┐
              │           OUTSIDE WORLD                   │
              │                                           │
    HTTP   →  │  [HTTP Adapter]   [CLI Adapter]           │
    CLI    →  │       │                │                  │
              │       ▼                ▼                  │
              │  ┌─────────────────────────────────────┐  │
              │  │         PRIMARY PORTS               │  │
              │  │   (driving ports — inputs)          │  │
              │  │  ┌───────────────────────────────┐  │  │
              │  │  │    APPLICATION CORE            │  │  │
              │  │  │    (pure business logic)       │  │  │
              │  │  └───────────────────────────────┘  │  │
              │  │         SECONDARY PORTS             │  │
              │  │   (driven ports — outputs)          │  │
              │  └─────────────────────────────────────┘  │
              │       │                │                  │
              │       ▼                ▼                  │
              │  [DB Adapter]   [Email Adapter]           │
              │                                           │
              └──────────────────────────────────────────┘

คำศัพท์ที่ต้องรู้:

Port — คือ interface (Python Protocol หรือ abstract class) ประกาศไว้ ข้างใน application core และเป็นเส้นแบ่งระหว่าง core กับโลกภายนอก

Adapter — คือ implementation จริง ของ port อยู่ ข้างนอก application core คอยต่อ core เข้ากับเทคโนโลยีจริง (database, HTTP framework, message queue)

Primary (Driving) Port — API ที่ application เปิดให้ข้างนอกใช้ ข้างนอกเป็นฝ่ายเรียกเข้ามา เช่น TodoService.create_todo(), UserService.login()

Secondary (Driven) Port — ของที่ application ต้องใช้จากข้างนอก application เป็นฝ่ายเรียกออกไป เช่น TodoRepository.save(), EmailSender.send_welcome()

โครงสร้างโปรเจกต์แบบ Hexagonal

my_app/
│
├── core/                            # The hexagon itself
│   ├── domain/
│   │   ├── todo.py                  # Entity
│   │   ├── user.py                  # Entity
│   │   └── events.py                # Domain Events
│   │
│   ├── ports/
│   │   ├── primary/                 # Driving ports (interfaces the adapters call INTO)
│   │   │   ├── todo_service_port.py
│   │   │   └── user_service_port.py
│   │   └── secondary/               # Driven ports (interfaces the core calls OUT TO)
│   │       ├── todo_repository_port.py
│   │       ├── user_repository_port.py
│   │       └── email_sender_port.py
│   │
│   └── services/                    # Application logic (implements primary ports)
│       ├── todo_service.py
│       └── user_service.py
│
└── adapters/
    ├── primary/                     # Driving adapters (call into the core)
    │   ├── http/
    │   │   ├── todo_router.py       # FastAPI routes
    │   │   └── user_router.py
    │   └── cli/
    │       └── seed_data.py
    └── secondary/                   # Driven adapters (called by the core)
        ├── persistence/
        │   ├── sql_todo_repository.py  # implements TodoRepositoryPort
        │   └── sql_user_repository.py  # implements UserRepositoryPort
        └── notifications/
            └── sendgrid_email_sender.py # implements EmailSenderPort

Part 4: เทียบกันชัดๆ

ประเด็น Clean Architecture Hexagonal Architecture
ภาพที่ใช้ วงกลมซ้อนกัน (layer) หกเหลี่ยม (ข้างใน vs ข้างนอก)
ผู้คิด Robert C. Martin, 2017 Alistair Cockburn, 2005
แนวคิดหลัก Dependency Rule ข้ามวงแหวน Port (interface) กับ Adapter (implementation)
คำศัพท์ Domain, Application, Infrastructure, Presentation Core, Primary Ports, Secondary Ports, Adapters
จำนวน layer 4 layer มีชื่อชัด 2 โซน: ข้างใน (core) กับข้างนอก (adapter)
use case อยู่ไหน วงแหวน Application Core service
interface อยู่ไหน วงแหวน Application (abstraction) Core port (แยก primary/secondary)
วิธี test Test แต่ละวงแหวนแยกกัน Test core ด้วย in-memory adapter
เข้ากับ DDD ดีมาก (วงแหวน Domain = DDD aggregate) ดีมาก (Core domain = DDD aggregate)
เหมาะกับ Domain ซับซ้อน use case เยอะ ระบบที่ต่อกับของภายนอกหลายจุด

พูดกันตรงๆ สองแบบนี้แก้ปัญหาเดียวกัน แค่เน้นคนละจุด Clean Architecture จัดโครงสร้างข้างในละเอียดกว่า (4 วงแหวน) ส่วน Hexagonal Architecture ไปจัดที่ขอบละเอียดกว่า (แยก primary กับ secondary port) codebase ที่โตแล้วหลายตัวก็ใช้คำศัพท์ทั้งสองชุดปนกัน


Part 5: โค้ดเต็ม — Clean Architecture ใน Python

มาลองสร้างระบบ Todo เล็กๆ ที่รันได้จริงด้วย Clean Architecture กัน

Domain Layer — Business Logic ล้วนๆ

# domain/todos/todo_item.py
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import Optional
from uuid import UUID, uuid4


class Priority(str, Enum):
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"


@dataclass
class TodoItem:
    title: str
    priority: Priority
    id: UUID = field(default_factory=uuid4)
    completed_at: Optional[datetime] = None
    created_at: datetime = field(default_factory=datetime.utcnow)

    # Business rule lives HERE, not in a service
    def complete(self) -> None:
        if self.completed_at is not None:
            raise ValueError("Todo is already completed.")
        self.completed_at = datetime.utcnow()

    @property
    def is_completed(self) -> bool:
        return self.completed_at is not None
# domain/todos/todo_errors.py
class TodoNotFoundError(Exception):
    def __init__(self, todo_id):
        super().__init__(f"Todo {todo_id} not found.")

class TodoAlreadyCompletedError(Exception):
    pass

Application Layer — Use Case + Interface

# application/abstractions/repositories.py
from abc import ABC, abstractmethod
from typing import Optional
from uuid import UUID
from domain.todos.todo_item import TodoItem


class TodoRepository(ABC):
    """Abstract interface — defined here, implemented in Infrastructure."""

    @abstractmethod
    def get_by_id(self, todo_id: UUID) -> Optional[TodoItem]: ...

    @abstractmethod
    def save(self, todo: TodoItem) -> None: ...

    @abstractmethod
    def delete(self, todo_id: UUID) -> None: ...
# application/todos/create_todo.py
from dataclasses import dataclass
from uuid import UUID
from domain.todos.todo_item import TodoItem, Priority
from application.abstractions.repositories import TodoRepository


@dataclass
class CreateTodoCommand:
    title: str
    priority: Priority


@dataclass
class CreateTodoResult:
    todo_id: UUID


class CreateTodoHandler:
    def __init__(self, repository: TodoRepository) -> None:
        self._repository = repository

    def handle(self, command: CreateTodoCommand) -> CreateTodoResult:
        todo = TodoItem(title=command.title, priority=command.priority)
        self._repository.save(todo)
        return CreateTodoResult(todo_id=todo.id)
# application/todos/complete_todo.py
from dataclasses import dataclass
from uuid import UUID
from application.abstractions.repositories import TodoRepository
from domain.todos.todo_errors import TodoNotFoundError


@dataclass
class CompleteTodoCommand:
    todo_id: UUID


class CompleteTodoHandler:
    def __init__(self, repository: TodoRepository) -> None:
        self._repository = repository

    def handle(self, command: CompleteTodoCommand) -> None:
        todo = self._repository.get_by_id(command.todo_id)
        if todo is None:
            raise TodoNotFoundError(command.todo_id)

        todo.complete()  # business rule enforced by the entity
        self._repository.save(todo)

Infrastructure Layer — Implementation จริง

# infrastructure/database/sql_todo_repository.py
from typing import Optional
from uuid import UUID
from sqlalchemy.orm import Session
from application.abstractions.repositories import TodoRepository
from domain.todos.todo_item import TodoItem, Priority
from infrastructure.database.models import TodoModel  # ORM model


class SqlTodoRepository(TodoRepository):
    """Concrete implementation — depends on SQLAlchemy. Application layer never imports this."""

    def __init__(self, session: Session) -> None:
        self._session = session

    def get_by_id(self, todo_id: UUID) -> Optional[TodoItem]:
        model = self._session.get(TodoModel, str(todo_id))
        if model is None:
            return None
        return TodoItem(
            id=UUID(model.id),
            title=model.title,
            priority=Priority(model.priority),
            completed_at=model.completed_at,
            created_at=model.created_at,
        )

    def save(self, todo: TodoItem) -> None:
        model = self._session.get(TodoModel, str(todo.id))
        if model is None:
            model = TodoModel(id=str(todo.id))
            self._session.add(model)
        model.title = todo.title
        model.priority = todo.priority.value
        model.completed_at = todo.completed_at
        self._session.flush()

    def delete(self, todo_id: UUID) -> None:
        model = self._session.get(TodoModel, str(todo_id))
        if model:
            self._session.delete(model)

Presentation Layer — FastAPI Endpoint

# presentation/api/endpoints/todos.py
from fastapi import APIRouter, Depends, HTTPException, status
from uuid import UUID
from pydantic import BaseModel
from application.todos.create_todo import CreateTodoCommand, CreateTodoHandler
from application.todos.complete_todo import CompleteTodoCommand, CompleteTodoHandler
from domain.todos.todo_item import Priority
from domain.todos.todo_errors import TodoNotFoundError

router = APIRouter(prefix="/todos", tags=["Todos"])


class CreateTodoRequest(BaseModel):
    title: str
    priority: Priority = Priority.MEDIUM


class CreateTodoResponse(BaseModel):
    todo_id: UUID


@router.post("/", response_model=CreateTodoResponse, status_code=status.HTTP_201_CREATED)
def create_todo(
    request: CreateTodoRequest,
    handler: CreateTodoHandler = Depends(),  # injected by DI container
):
    command = CreateTodoCommand(title=request.title, priority=request.priority)
    result = handler.handle(command)
    return CreateTodoResponse(todo_id=result.todo_id)


@router.patch("/{todo_id}/complete", status_code=status.HTTP_204_NO_CONTENT)
def complete_todo(
    todo_id: UUID,
    handler: CompleteTodoHandler = Depends(),
):
    try:
        handler.handle(CompleteTodoCommand(todo_id=todo_id))
    except TodoNotFoundError as e:
        raise HTTPException(status_code=404, detail=str(e))

Dependency Injection — ประกอบทุกชิ้นเข้าด้วยกัน

# presentation/dependency_injection.py
from functools import lru_cache
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
from fastapi import Depends
from application.todos.create_todo import CreateTodoHandler
from application.todos.complete_todo import CompleteTodoHandler
from infrastructure.database.sql_todo_repository import SqlTodoRepository

engine = create_engine("postgresql://user:pass@localhost/myapp")
SessionLocal = sessionmaker(bind=engine)


def get_db() -> Session:
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def get_todo_repository(db: Session = Depends(get_db)) -> SqlTodoRepository:
    return SqlTodoRepository(db)


def get_create_todo_handler(
    repo: SqlTodoRepository = Depends(get_todo_repository),
) -> CreateTodoHandler:
    return CreateTodoHandler(repository=repo)


def get_complete_todo_handler(
    repo: SqlTodoRepository = Depends(get_todo_repository),
) -> CompleteTodoHandler:
    return CompleteTodoHandler(repository=repo)

Part 6: โค้ดเต็ม — Hexagonal Architecture ใน Python

ระบบ Todo ตัวเดิม แต่คราวนี้เขียนแบบ Hexagonal logic เหมือนเดิมทุกอย่าง ต่างกันแค่โครงสร้าง

Core: Domain + Port

# core/ports/secondary/todo_repository_port.py
from typing import Protocol, Optional
from uuid import UUID
from core.domain.todo import TodoItem


class TodoRepositoryPort(Protocol):
    """Secondary port — the core's requirement from storage. Any adapter can implement this."""

    def get_by_id(self, todo_id: UUID) -> Optional[TodoItem]: ...
    def save(self, todo: TodoItem) -> None: ...
    def delete(self, todo_id: UUID) -> None: ...
# core/ports/primary/todo_service_port.py
from typing import Protocol
from uuid import UUID
from core.domain.todo import Priority


class TodoServicePort(Protocol):
    """Primary port — what the outside world can call on this application."""

    def create_todo(self, title: str, priority: Priority) -> UUID: ...
    def complete_todo(self, todo_id: UUID) -> None: ...
    def delete_todo(self, todo_id: UUID) -> None: ...
# core/services/todo_service.py
from uuid import UUID
from core.domain.todo import TodoItem, Priority
from core.ports.secondary.todo_repository_port import TodoRepositoryPort


class TodoService:
    """Implements the primary port. Depends only on secondary ports."""

    def __init__(self, repository: TodoRepositoryPort) -> None:
        self._repository = repository

    def create_todo(self, title: str, priority: Priority) -> UUID:
        todo = TodoItem(title=title, priority=priority)
        self._repository.save(todo)
        return todo.id

    def complete_todo(self, todo_id: UUID) -> None:
        todo = self._repository.get_by_id(todo_id)
        if todo is None:
            raise ValueError(f"Todo {todo_id} not found.")
        todo.complete()
        self._repository.save(todo)

Adapter: Primary (HTTP) และ Secondary (Database)

# adapters/primary/http/todo_router.py
from fastapi import APIRouter, HTTPException
from uuid import UUID
from pydantic import BaseModel
from core.domain.todo import Priority
from core.ports.primary.todo_service_port import TodoServicePort

router = APIRouter(prefix="/todos", tags=["Todos"])


class CreateTodoRequest(BaseModel):
    title: str
    priority: Priority = Priority.MEDIUM


# The adapter calls INTO the core through the primary port
def make_todo_router(service: TodoServicePort) -> APIRouter:
    @router.post("/")
    def create(req: CreateTodoRequest):
        todo_id = service.create_todo(req.title, req.priority)
        return {"todo_id": str(todo_id)}

    @router.patch("/{todo_id}/complete")
    def complete(todo_id: UUID):
        try:
            service.complete_todo(todo_id)
        except ValueError as e:
            raise HTTPException(status_code=404, detail=str(e))

    return router
# adapters/secondary/persistence/sql_todo_repository.py
from typing import Optional
from uuid import UUID
from sqlalchemy.orm import Session
from core.domain.todo import TodoItem, Priority
from core.ports.secondary.todo_repository_port import TodoRepositoryPort
from adapters.secondary.persistence.models import TodoModel


class SqlTodoRepository:
    """Secondary adapter — implements the core's TodoRepositoryPort."""

    def __init__(self, session: Session) -> None:
        self._session = session

    def get_by_id(self, todo_id: UUID) -> Optional[TodoItem]:
        model = self._session.get(TodoModel, str(todo_id))
        if model is None:
            return None
        return TodoItem(id=UUID(model.id), title=model.title,
                        priority=Priority(model.priority))

    def save(self, todo: TodoItem) -> None:
        model = self._session.merge(TodoModel(
            id=str(todo.id), title=todo.title,
            priority=todo.priority.value, completed_at=todo.completed_at,
        ))
        self._session.flush()

    def delete(self, todo_id: UUID) -> None:
        model = self._session.get(TodoModel, str(todo_id))
        if model:
            self._session.delete(model)

In-Memory Adapter — ตัวช่วยที่ทำให้ test ง่ายสุดๆ

นี่คือประโยชน์ที่จับต้องได้มากที่สุดของทั้งสองแบบ:

# tests/fakes/in_memory_todo_repository.py
from typing import Optional
from uuid import UUID
from core.domain.todo import TodoItem


class InMemoryTodoRepository:
    """A test double that satisfies TodoRepositoryPort with no database needed."""

    def __init__(self):
        self._store: dict[UUID, TodoItem] = {}

    def get_by_id(self, todo_id: UUID) -> Optional[TodoItem]:
        return self._store.get(todo_id)

    def save(self, todo: TodoItem) -> None:
        self._store[todo.id] = todo

    def delete(self, todo_id: UUID) -> None:
        self._store.pop(todo_id, None)


# test_todo_service.py
def test_completing_a_todo_marks_it_as_done():
    repo = InMemoryTodoRepository()
    service = TodoService(repository=repo)

    todo_id = service.create_todo("Write unit tests", Priority.HIGH)
    service.complete_todo(todo_id)

    todo = repo.get_by_id(todo_id)
    assert todo.is_completed is True
    # No database. No FastAPI. No HTTP. Runs in milliseconds.

Part 7: จุดที่คนส่วนใหญ่ทำพลาด

คำโปรยใต้ diagram ที่ว่า "And what most people get wrong" ควรแยกออกมาเป็นหัวข้อเลย เพราะข้อผิดพลาดพวกนี้เจอกันแทบทุกทีม

Mistake 1: Application ไป import Infrastructure

# WRONG — Application use case importing SQLAlchemy directly
from sqlalchemy.orm import Session  # ← Infrastructure bleeds into Application

class CreateTodoHandler:
    def __init__(self, session: Session):  # ← Application now depends on SQLAlchemy
        self._session = session

วิธีแก้: ให้ Application layer ประกาศ TodoRepository แบบ abstract ไว้ ส่วน Session ให้อยู่แค่ใน Infrastructure layer

Mistake 2: Anemic Domain — Logic ไปกองอยู่ใน Service แทน Entity

# WRONG — business rule in the Application layer
class CompleteTodoHandler:
    def handle(self, command):
        todo = self._repository.get_by_id(command.todo_id)
        todo.completed_at = datetime.utcnow()  # ← sets field directly, no validation
        self._repository.save(todo)

# RIGHT — business rule in the Domain entity
class TodoItem:
    def complete(self) -> None:
        if self.completed_at is not None:
            raise TodoAlreadyCompletedError()  # ← invariant enforced here
        self.completed_at = datetime.utcnow()

Entity ต้องรู้กฎของตัวเอง ถ้า service ข้าม method ของ entity ไปแก้ field ตรงๆ ก็เท่ากับทำลาย domain model

Mistake 3: Repository ยักษ์ตัวเดียว

# WRONG
class TodoRepository:
    def get_by_id(self): ...
    def get_all(self): ...
    def get_by_user_id(self): ...
    def get_overdue(self): ...
    def get_completed_between(self): ...
    def get_priority_stats(self): ...  # now this is a reporting query, not a repository

วิธีแก้: แยก query ฝั่งอ่านที่มีเยอะๆ ออกไปเป็น Query Service หรือใช้ CQRS pattern ไปเลย Command (เขียน) วิ่งผ่าน Domain ส่วน Query (อ่าน) ยิงตรงไปที่ database ด้วย raw SQL หรือ query builder ถ้าบังคับให้ทุก query ต้องผ่าน domain entity จะเปลืองแรงโดยไม่จำเป็น

Mistake 4: ไม่ใช้ Dependency Injection Container

ทั้งสองแบบต้อง inject implementation จริงเข้ามาจากข้างนอก ถ้าไม่มี DI container ก็จะได้ main.py ที่มีฟังก์ชันประกอบ dependency ยาวเหยียด หรือแย่กว่านั้น use case เริ่มไป import concrete class เอง

จะใช้ Depends ของ FastAPI, library dependency-injector ของ Python หรือ factory pattern ง่ายๆ ก็ได้ ขอแค่ข้อเดียว: use case หรือ domain object ห้ามเรียก SqlTodoRepository() เองเด็ดขาด

Mistake 5: เอา Clean Architecture ไปใช้กับแอป CRUD ธรรมดา

Clean Architecture overhead is real:
  Simple CRUD endpoint: 3 files in Flask
  Same endpoint in Clean Architecture: 7+ files across 4 layers

If your app is: simple CRUD, <5 entities, single developer
Then: Flask/FastAPI with a thin service layer is perfectly correct

If your app is: complex domain, multiple teams, long-lived codebase
Then: Clean Architecture pays for itself quickly

Part 8: จะเลือกแบบไหนดี

"I want a clear, ring-based structure with a strong convention for
 every type of object — and I'm comfortable with 4 named layers."
  → Clean Architecture

"I want to maximize testability and focus on the boundary between
 my application and external systems — I have many integrations."
  → Hexagonal Architecture (Ports & Adapters)

"I want both — a domain-rich core AND explicit port/adapter naming
 for every integration point."
  → Use them together. Most production systems do.
  → The rings come from Clean; the port/adapter naming at the
    boundary comes from Hexagonal.

ทีมที่มีประสบการณ์มักใช้โครงสร้าง folder แบบ Clean Architecture (domain / application / infrastructure / presentation) แล้วก็ เรียก interface ว่า "port" เรียก implementation ว่า "adapter" ไปด้วย ได้ข้อดีของคำศัพท์ทั้งสองชุด


Summary

Clean Architecture กับ Hexagonal Architecture ยึดหลักข้อเดียวกัน: business logic ต้องไม่พึ่ง infrastructure เด็ดขาด dependency ชี้เข้าด้านใน application เป็นคนกำหนด interface ส่วน implementation จริงอยู่ข้างนอก

Clean Architecture แบ่งเป็นวงแหวนซ้อนกันสี่วงที่มีชื่อชัดเจน คือ Domain, Application, Infrastructure และ Presentation กฎมีข้อเดียว วงนอกพึ่งวงในได้ แต่ห้ามกลับกัน เหมาะมากกับระบบที่ domain ซับซ้อน business rule เยอะ และมี use case จำนวนมากที่ต้องจัดให้เป็นระเบียบ

Hexagonal Architecture (Ports and Adapters) แบ่งเป็นสองโซน คือ application core กับโลกภายนอก เชื่อมกันด้วย interface ที่เรียกว่า port และ implementation ที่เรียกว่า adapter เหมาะกับระบบที่ต่อกับของภายนอกหลายจุด และอยาก test core แบบแยกขาดจากทุกอย่างได้เต็มที่

ความผิดพลาดห้าข้อที่ทำให้ implementation ส่วนใหญ่พัง: import infrastructure เข้ามาใน application layer, เอา business logic ไปไว้ใน service แทน entity, ยัดทุกอย่างไว้ใน repository ก้อนเดียว, ไม่ใช้ dependency injection และเอา pattern ไหนก็ตามไปใช้กับแอป CRUD ธรรมดา ซึ่งมีแต่ต้นทุนเพิ่มโดยไม่ได้ประโยชน์อะไร

ถ้าจะเริ่มโปรเจกต์ใหม่ ผมแนะนำแบบนี้: ใช้โครงสร้าง folder สี่วงแหวนของ Clean Architecture ตั้งชื่อ interface ใน Application layer ให้ชัด และเขียน in-memory adapter fake ให้ทุก secondary port ตั้งแต่วันแรก แค่นี้ test suite ก็จะช่วยคุณไปอีกหลายปี


อยากได้ GitHub repository ที่รันได้จริงตามโครงสร้างนี้ พร้อม Docker Compose, Alembic migration และ pytest setup ไหม? ทิ้งคอมเมนต์ไว้ด้านล่างได้เลย

มีคำถามหรืออยากคุยต่อ ทักผมได้ทาง LinkedIn, X หรือ email

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.