Files
2nd/10_Wiki/Topics/Domain_Programming/Architecture/High-Cohesion-Low-Coupling.md
T
Antigravity Agent c24165b8bc refactor(topics): 멀티 에이전트용 지식 재편 — _Common(공통 기본기) + Domain_* 구조
에이전트 8종(대화형/프로그래머 C·S/디자이너/설계자/기획자/QA/PD/PM)에게
[공통 기본 능력 + 롤별 Specialty] 2층으로 지식을 주입하기 위한 재분류.
문서 내용·포맷은 무수정, 폴더 이동만 (6,372개 문서 수 보존 확인).

- Topic_Programming → Domain_Programming (내부 구조 보존)
- Topic_Graphic → Domain_Design
- Topic_Business → Domain_Product
- Topic_General → Domain_General
- _Common 신설: Math(구 Topic_Math_Specialty), Reasoning(구 General/From_Thinking & Reasoning),
  Reasoning_Creativity(구 General/From_창의성), Communication(Poetic_Blog_Writing + From_writing)
- 타 도메인의 From_* 폴더는 유지 (출처 표기일 뿐, 이미 도메인에 맞게 분류된 문서)
- 빈 폴더 정리 (memory/procedures)
- 에이전트→폴더 매핑은 workspace의 .astra/agent-knowledge-map.json (9개 에이전트)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 11:05:56 +09:00

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 |