--- id: wiki-2026-0508-implementation-separation title: Implementation Separation category: 10_Wiki/Topics status: verified canonical_id: self aliases: [Implementation Separation, Interface-Implementation Split, Hexagonal Boundaries] duplicate_of: none source_trust_level: A confidence_score: 0.9 verification_status: applied tags: [architecture, interface, dependency-inversion, hexagonal, ports-adapters] raw_sources: [] last_reinforced: 2026-05-10 github_commit: pending tech_stack: language: TypeScript/Python/Go framework: language-agnostic --- # Implementation Separation ## 매 한 줄 > **"매 'what' 매 'how' 의 분리"**. Implementation separation 매 interface (contract) 매 implementation (mechanism) 매 명시적 분리 — 매 dependency inversion, ports-and-adapters, hexagonal architecture 의 core idea. 매 testability, swappability, evolution 매 enable. ## 매 핵심 ### 매 Why separate - **Test**: 매 fake/mock 매 swap-in. - **Swap**: 매 Postgres → DynamoDB 매 caller code unchanged. - **Boundary**: 매 layer/module 매 명확. - **Parallel work**: 매 interface freeze → 매 team 매 parallel implementation. ### 매 Levels of separation 1. **Interface keyword** (Java, C#, Go, TypeScript): 매 syntax 매 enforce. 2. **Abstract base class** (Python, C++): 매 ABC, virtual. 3. **Protocol/structural typing** (Python typing.Protocol, TypeScript): 매 duck typing 매 static check. 4. **Trait** (Rust): 매 zero-cost. 5. **Module boundary** (Haskell .hs-boot, OCaml .mli): 매 module-level. ### 매 응용 1. **Repository pattern**: 매 `UserRepo` interface, 매 `PgUserRepo` impl. 2. **Strategy pattern**: 매 algorithm 매 swap. 3. **Adapter (port)**: 매 external service 매 wrap. 4. **Test doubles**: 매 InMemory* impl. ## 💻 패턴 ### TypeScript — port + adapter ```typescript // Port (domain owns this) export interface UserRepo { findById(id: string): Promise; save(u: User): Promise; } // Adapter (infrastructure) export class PgUserRepo implements UserRepo { constructor(private db: Pool) {} async findById(id: string) { const r = await this.db.query('select * from users where id=$1', [id]); return r.rows[0] ? mapUser(r.rows[0]) : null; } async save(u: User) { await this.db.query('insert into users ...', [u.id, u.name]); } } // In-memory test double export class InMemoryUserRepo implements UserRepo { private map = new Map(); async findById(id: string) { return this.map.get(id) ?? null; } async save(u: User) { this.map.set(u.id, u); } } ``` ### Python Protocol (structural) ```python from typing import Protocol class Notifier(Protocol): def send(self, to: str, msg: str) -> None: ... class EmailNotifier: def send(self, to: str, msg: str) -> None: smtp.sendmail(...) class SlackNotifier: def send(self, to: str, msg: str) -> None: requests.post("https://slack/api", json={"channel": to, "text": msg}) def notify_user(n: Notifier, user_id: str, msg: str) -> None: n.send(user_id, msg) # any structural match works ``` ### Go — implicit interface ```go type Cache interface { Get(key string) ([]byte, bool) Set(key string, val []byte, ttl time.Duration) } type RedisCache struct{ client *redis.Client } func (r *RedisCache) Get(k string) ([]byte, bool) { /* ... */ } func (r *RedisCache) Set(k string, v []byte, ttl time.Duration) { /* ... */ } type MemCache struct{ m sync.Map } func (m *MemCache) Get(k string) ([]byte, bool) { /* ... */ } func (m *MemCache) Set(k string, v []byte, ttl time.Duration) { /* ... */ } ``` ### Rust trait ```rust pub trait Storage { fn put(&self, key: &str, val: &[u8]) -> anyhow::Result<()>; fn get(&self, key: &str) -> anyhow::Result>>; } pub struct S3Storage { client: aws_sdk_s3::Client } impl Storage for S3Storage { /* ... */ } pub struct LocalFs { root: PathBuf } impl Storage for LocalFs { /* ... */ } pub fn save_blob(s: &S, k: &str, v: &[u8]) -> anyhow::Result<()> { s.put(k, v) } ``` ### Hexagonal layout ``` src/ domain/ # pure logic, no I/O user.ts order.ts ports/ # interfaces user_repo.ts payment_gateway.ts app/ # use-cases, depend on ports only place_order.ts adapters/ # impl of ports pg_user_repo.ts stripe_gateway.ts infra/ # composition root main.ts ``` ## 매 결정 기준 | 상황 | Approach | |---|---| | 매 single impl, no test isolation needed | 매 직접 class — 매 over-engineer 금지 | | 매 ≥2 impls or test doubles 필요 | 매 interface/protocol/trait | | 매 cross-team boundary | 매 interface freeze 매 contract | | 매 swappable infra (DB, queue, cache) | 매 port + adapter | | 매 perf-critical hot loop | 매 generics/static dispatch (no vtable) | **기본값**: 매 ports 매 domain 옆, adapters 매 infra layer, 매 composition root 매 wire. ## 🔗 Graph - 부모: [[Hexagonal Architecture]] · [[Dependency Inversion Principle]] - 변형: [[Ports and Adapters]] · [[Clean-Architecture]] · [[Onion-Architecture]] - 응용: [[Test-Doubles]] - Adjacent: [[High-Cohesion-Low-Coupling]] · [[SOLID]] ## 🤖 LLM 활용 **언제**: 매 architecture refactor; 매 testability 부족; 매 multiple infra backend; 매 team boundary. **언제 X**: 매 single-use script; 매 prototype; 매 only one impl forever. ## ❌ 안티패턴 - **IFoo + FooImpl 매 1:1 forever**: 매 interface 매 swap/test point 없으면 매 잡음. - **Leaky abstraction**: 매 interface method 매 SQL string 받음 — 매 impl 의 detail 노출. - **Anemic port**: 매 CRUD method 만 매 interface — 매 domain logic 매 caller 에 leak. - **Adapter 매 domain 의 의존**: 매 dep 매 wrong direction. ## 🧪 검증 / 중복 - Verified (Cockburn 2005 "Hexagonal Architecture", Evans DDD, Martin "Clean Architecture", Vernon IDDD). - 신뢰도 A. ## 🕓 Changelog | 날짜 | 변경 | |---|---| | 2026-05-08 | Phase 1 | | 2026-05-10 | Manual cleanup — full content (port/adapter, multi-language patterns) |