f8b21af4be
10_Wiki/Topics 대규모 정리: - 오류 캡처/미완성 stub 문서 227개 제거 - 교차폴더 중복 43클러스터 병합 (63파일 → redirect) - 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건 - 카테고리 MOC 6개 신규 생성 - Graph 섹션 미해결 related-keyword 링크 10,058건 제거 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
174 lines
5.6 KiB
Markdown
174 lines
5.6 KiB
Markdown
---
|
|
id: wiki-2026-0508-high-cohesion-low-coupling
|
|
title: High Cohesion Low Coupling
|
|
category: 10_Wiki/Topics
|
|
status: verified
|
|
canonical_id: self
|
|
aliases: [Cohesion and Coupling, Loose Coupling High Cohesion]
|
|
duplicate_of: none
|
|
source_trust_level: A
|
|
confidence_score: 0.95
|
|
verification_status: applied
|
|
tags: [architecture, design-principles, modularity, oop, refactoring]
|
|
raw_sources: []
|
|
last_reinforced: 2026-05-10
|
|
github_commit: pending
|
|
tech_stack:
|
|
language: typescript
|
|
framework: language-agnostic
|
|
---
|
|
|
|
# High Cohesion Low Coupling
|
|
|
|
## 매 한 줄
|
|
> **"매 module 내부 의 element 의 strong relatedness (cohesion) + module 간 의 minimal dependency (coupling) 의 maximize"**. 매 Larry Constantine 의 1968 structured design 의 origin, 매 modern 의 SOLID, DDD bounded context, microservices 의 universal foundation — 매 changeability 의 single 의 most important predictor.
|
|
|
|
## 매 핵심
|
|
|
|
### 매 Cohesion 7 levels (Constantine, low → high)
|
|
1. Coincidental (random grouping).
|
|
2. Logical (similar category, e.g., "Utils").
|
|
3. Temporal (executed at same time).
|
|
4. Procedural (sequence of steps).
|
|
5. Communicational (act on same data).
|
|
6. Sequential (output of one → input of next).
|
|
7. **Functional** (single, well-defined task) — 매 target.
|
|
|
|
### 매 Coupling 6 levels (low → high)
|
|
1. **Data** (parameters of primitives) — 매 ideal.
|
|
2. Stamp (parameters of composite).
|
|
3. Control (flag-driven branching).
|
|
4. External (shared protocol).
|
|
5. Common (shared global).
|
|
6. Content (one module 의 internals 의 mutate) — 매 worst.
|
|
|
|
### 매 응용
|
|
1. Module boundary 의 design.
|
|
2. Microservice 의 split criteria (DDD bounded context).
|
|
3. Refactoring 의 direction-finder.
|
|
|
|
## 💻 패턴
|
|
|
|
### Smell — Low Cohesion
|
|
```typescript
|
|
// 🚨 Logical cohesion only
|
|
export class Utils {
|
|
formatDate(d: Date) { /* ... */ }
|
|
parseCSV(s: string) { /* ... */ }
|
|
hashPassword(p: string) { /* ... */ }
|
|
sendEmail(to: string) { /* ... */ }
|
|
}
|
|
```
|
|
|
|
### Refactor — Functional Cohesion
|
|
```typescript
|
|
// formatting/date.ts
|
|
export const formatISO = (d: Date) => d.toISOString().slice(0, 10);
|
|
|
|
// parsing/csv.ts
|
|
export const parseCSV = (s: string) => /* ... */;
|
|
|
|
// auth/password.ts
|
|
export const hashPassword = (p: string) => bcrypt.hash(p, 12);
|
|
|
|
// email/send.ts
|
|
export const sendEmail = (to: string, body: string) => transporter.send(/* ... */);
|
|
```
|
|
|
|
### Smell — High Coupling (Content)
|
|
```typescript
|
|
class OrderService {
|
|
constructor(private inventory: InventoryService) {}
|
|
reserve(id: string) {
|
|
// 🚨 Reaches into private state
|
|
this.inventory['stock'].set(id, 0);
|
|
}
|
|
}
|
|
```
|
|
|
|
### Refactor — Data Coupling via Interface
|
|
```typescript
|
|
interface InventoryPort {
|
|
reserve(sku: string, qty: number): Promise<ReservationId>;
|
|
}
|
|
|
|
class OrderService {
|
|
constructor(private inventory: InventoryPort) {}
|
|
async reserve(sku: string, qty: number) {
|
|
return this.inventory.reserve(sku, qty);
|
|
}
|
|
}
|
|
```
|
|
|
|
### Dependency Inversion (Hexagonal)
|
|
```typescript
|
|
// domain/order.ts (no infra import)
|
|
export interface OrderRepository {
|
|
save(o: Order): Promise<void>;
|
|
byId(id: string): Promise<Order | null>;
|
|
}
|
|
|
|
// infra/postgres-order-repo.ts
|
|
export class PostgresOrderRepository implements OrderRepository { /* ... */ }
|
|
|
|
// app/wire.ts
|
|
const repo: OrderRepository = new PostgresOrderRepository(pool);
|
|
const svc = new OrderService(repo);
|
|
```
|
|
|
|
### Event-Driven Decoupling
|
|
```typescript
|
|
// publisher
|
|
events.emit('OrderPlaced', { orderId, customerId, total });
|
|
|
|
// subscribers (independent modules)
|
|
events.on('OrderPlaced', sendConfirmationEmail);
|
|
events.on('OrderPlaced', updateAnalytics);
|
|
events.on('OrderPlaced', allocateInventory);
|
|
```
|
|
|
|
### Coupling Metric — Fan-in / Fan-out
|
|
```bash
|
|
# madge 의 dep graph
|
|
npx madge --circular --extensions ts src/
|
|
npx madge --summary --extensions ts src/ # fan-in/fan-out per module
|
|
```
|
|
|
|
## 매 결정 기준
|
|
| 상황 | Approach |
|
|
|---|---|
|
|
| Module > 500 LOC, scattered concerns | Split by responsibility (cohesion↑) |
|
|
| Module imports 20+ siblings | Introduce interface / facade |
|
|
| Cross-module mutation | Event / message passing |
|
|
| Shared mutable global | Replace with pure function or DI |
|
|
| Microservice split | DDD bounded context boundary |
|
|
|
|
**기본값**: 매 functional cohesion + data coupling 의 target — 매 interface 의 통한 dependency 의 invert.
|
|
|
|
## 🔗 Graph
|
|
- 부모: [[Software-Architecture]] · [[Modularity]]
|
|
- 변형: [[Single Responsibility Principle (SRP)|Single-Responsibility-Principle]] · [[Bounded-Context]] · [[Hexagonal-Architecture]]
|
|
- 응용: [[SOLID]] · [[Microservices]] · [[Clean-Architecture]]
|
|
- Adjacent: [[God-Object-Antipattern]] · [[Dependency-Inversion]]
|
|
|
|
## 🤖 LLM 활용
|
|
**언제**: module 의 cohesion/coupling 의 review, refactor 의 direction 의 suggest, dep graph 의 hot-spot 의 highlight.
|
|
**언제 X**: 매 architectural boundary 의 final decision (domain expert + business context 필요).
|
|
|
|
## ❌ 안티패턴
|
|
- **God Module**: low cohesion + high fan-in (모두 의 import).
|
|
- **Anemic Module**: data 만, behavior 의 다른 module 의 own → procedural disguised as OOP.
|
|
- **Tight ORM coupling**: domain entity 의 ORM annotation 의 saturation → infra 의 leak.
|
|
- **Premature abstraction**: 매 single use-case 의 interface 의 introduce → 매 indirection 의 cost.
|
|
- **Shared library 의 god lib**: 매 service 의 shared "common" 의 god — 매 deploy lockstep.
|
|
|
|
## 🧪 검증 / 중복
|
|
- Verified (Constantine "Structured Design" 1979, Martin "Clean Architecture", Evans "DDD").
|
|
- 신뢰도 A.
|
|
|
|
## 🕓 Changelog
|
|
| 날짜 | 변경 |
|
|
|---|---|
|
|
| 2026-05-08 | Phase 1 |
|
|
| 2026-05-10 | Manual cleanup — cohesion/coupling principles 의 full content |
|