[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,93 +2,172 @@
|
||||
id: wiki-2026-0508-high-cohesion-low-coupling
|
||||
title: High Cohesion Low Coupling
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-HCLC-001]
|
||||
aliases: [Cohesion and Coupling, Loose Coupling High Cohesion]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.98
|
||||
tags: [auto-reinforced, software-craftsmanship, Modularity, Architecture, cohesion, coupling, design-patterns]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [architecture, design-principles, modularity, oop, refactoring]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: typescript
|
||||
framework: language-agnostic
|
||||
---
|
||||
|
||||
# [[High-Cohesion-Low-Coupling|High-Cohesion-Low-Coupling]]
|
||||
# High Cohesion Low Coupling
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "단단한 블록, 느슨한 연결: 하나의 모듈은 오직 하나의 목적에만 집중하여 내부를 꽉 채우고(Cohesion), 다른 모듈과는 최소한의 접점만 유지하여(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.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
고응집 저결합(High-Cohesion-Low-Coupling)은 소프트웨어 설계의 품질을 결정하는 가장 고전적이면서 강력한 원칙입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **High Cohesion (고응집)**:
|
||||
* 모듈 내부의 요소들이 하나의 책임(Single Responsibility)을 위해 얼마나 밀접하게 협력하는가. ([[DDD-Type-Safety|DDD-Type-Safety]]와 연결)
|
||||
* **장점**: 가독성 향상, 재사용성 증가.
|
||||
2. **Low Coupling (저결합)**:
|
||||
* 서로 다른 모듈 간의 의존성 강도.
|
||||
* **장점**: 한 곳의 변경 정책이 다른 곳에 미치는 영향 정책 최소화 (Side-effect 방지). ([[Reliability|Reliability]]와 연결)
|
||||
3. **왜 중요한가?**:
|
||||
* 복잡한 시스템 정책의 유지보수 비용 정책을 결정하며, 대규모 팀 협업 시 코드 충돌 정책을 방지하는 구조적 방패이기 때문임. (Modularity와 연결)
|
||||
### 매 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.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 모든 기능을 한 곳에 모으는 'Monolithic' 정책이 성능 면에서 우수하다고 믿었으나, 현대 정책은 코드베이스가 커짐에 따라 발생하는 'Dirty code 정책'의 비용 정책이 훨씬 커짐을 인지하고 마이크로서비스(MSA) 정책처럼 극단적인 저결합 정책을 지향함(RL Update).
|
||||
- **정책 변화(RL Update)**: 이제는 단순 코드 설계 정책을 넘어, 조직 구조 정책까지도 소프트웨어 아키텍처 정책과 일치시켜야 한다는 'Conway's Law'를 기반으로 팀 빌딩 정책에도 이 원칙 정책이 적용됨.
|
||||
### 매 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.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[DDD-Type-Safety|DDD-Type-Safety]], [[Reliability|Reliability]], [[Modularity|Modularity]], [[Technical-Architecture|Technical-Architecture]], Standard-Operating-Procedure, Clean-Code
|
||||
- **Key Principle**: SOLID [[Principles|Principles]].
|
||||
---
|
||||
### 매 응용
|
||||
1. Module boundary 의 design.
|
||||
2. Microservice 의 split criteria (DDD bounded context).
|
||||
3. Refactoring 의 direction-finder.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### Smell — Low Cohesion
|
||||
```typescript
|
||||
// 🚨 Logical cohesion only
|
||||
export class Utils {
|
||||
formatDate(d: Date) { /* ... */ }
|
||||
parseCSV(s: string) { /* ... */ }
|
||||
hashPassword(p: string) { /* ... */ }
|
||||
sendEmail(to: string) { /* ... */ }
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Refactor — Functional Cohesion
|
||||
```typescript
|
||||
// formatting/date.ts
|
||||
export const formatISO = (d: Date) => d.toISOString().slice(0, 10);
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// parsing/csv.ts
|
||||
export const parseCSV = (s: string) => /* ... */;
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// auth/password.ts
|
||||
export const hashPassword = (p: string) => bcrypt.hash(p, 12);
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
// email/send.ts
|
||||
export const sendEmail = (to: string, body: string) => transporter.send(/* ... */);
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Smell — High Coupling (Content)
|
||||
```typescript
|
||||
class OrderService {
|
||||
constructor(private inventory: InventoryService) {}
|
||||
reserve(id: string) {
|
||||
// 🚨 Reaches into private state
|
||||
this.inventory['stock'].set(id, 0);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### 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]] · [[Bounded-Context]] · [[Hexagonal-Architecture]]
|
||||
- 응용: [[SOLID]] · [[Microservices]] · [[Clean-Architecture]]
|
||||
- Adjacent: [[God-Object-Antipattern]] · [[Dependency-Inversion]] · [[Law-of-Demeter]]
|
||||
|
||||
## 🤖 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 |
|
||||
|
||||
Reference in New Issue
Block a user