[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,105 +2,166 @@
id: wiki-2026-0508-응집도와-결합도-cohesion-and-coupling
title: 응집도와 결합도 (Cohesion and Coupling)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-AECECF]
aliases: [Cohesion and Coupling, 응집도와 결합도, High Cohesion Low Coupling]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [software-design, modularity, architecture, fundamentals]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - 응집도와 결합도 (Cohesion and Coupling)"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: any
framework: any
---
# [[응집도와 결합도 (Cohesion and Coupling)|응집도와 결합도 (Cohesion and Coupling]]
# 응집도와 결합도 (Cohesion and Coupling)
## 📌 한 줄 통찰 (The Karpathy Summary)
> **응집도(Cohesion)**는 모듈 내부의 요소들이 하나의 명확한 목적을 위해 얼마나 밀접하게 관련되어 있는지를 측정하는 척도이며, **결합도(Coupling)**는 모듈 간의 상호 의존성 정도를 나타내는 척도이다 [1], [2], [3]. "관심사의 분리(SoC)" 원칙을 소프트웨어에 적용하는 핵심 과정은 **결합도를 낮추고(Loose Coupling) 응집도를 높이는(High Cohesion)** 것이다 [4], [5]. 이를 달성함으로써 시스템의 복잡성을 줄이고 가독성, 유지보수성, 테스트 가능성을 비약적으로 향상시킬 수 있다 [6], [7], [8].
## 한 줄
> **"매 high cohesion, low coupling"**. 1974년 Larry Constantine 의 structured design 으로 도입된 매 module quality metric 의 두 axis — module 내부 element 의 relatedness (cohesion) 와 module 간 dependency strength (coupling). 매 2026 microservice / domain-driven design 의 기본 vocabulary.
## 📖 구조화된 지식 (Synthesized Content)
**1. 응집도와 결합도의 개념**
* **응집도(Cohesion):** 모듈이나 클래스 내의 요소들이 직무의 집합이나 세부사항 측면에서 얼마나 유사하고 단일한 기능에 집중하고 있는지를 의미한다 [4], [2]. 이상적인 형태인 '기능적 응집'부터 순차적, 논리적, 시간적, 절차적, 그리고 가장 낮은 수준인 '우발적 응집'으로 분류할 수 있다 [2].
* **결합도(Coupling):** 한 모듈이 시스템의 나머지 부분이나 다른 모듈에 얼마나 의존하는지를 나타낸다 [9], [3]. 가장 강한 형태인 '내용 결합'부터 공통, 외부, 제어, 스탬프, 그리고 가장 이상적이고 약한 형태인 '자료 결합' 순으로 나뉜다 [3].
## 매 핵심
**2. 관심사의 분리(SoC)와의 관계**
* 관심사의 분리가 성공적으로 이루어졌는지를 판단하는 **정량적, 정성적 핵심 척도**가 바로 응집도와 결합도이다 [1].
* 내부의 결속력(상호작용)은 극대화하고 외부의 간섭은 최소화하는 것이 관심사 분리의 공학적 지향점이다 [10]. 이를 수학적 비유로 표현하면, 설계 품질은 모듈 내부의 상호작용 총합을 모듈 외부와의 상호작용 총합으로 나눈 값에 비례한다 [10].
* 만약 코드의 알고리즘 논리를 파악할 때 여러 기능이나 모듈 사이를 빈번하게 뛰어다니며 확인해야 한다면, 이는 응집도가 낮다는 신호이며 흔히 **'스파게티 코드(Spaghetti code)'**라 불리는 관리 불능 상태를 낳게 된다 [11], [12], [1].
### 매 Cohesion (응집도) — 매 within
- 매 single module element 가 매 single purpose 를 향하는 정도.
- 매 Higher = better. 매 module 의 reason to change 의 한 가지로 수렴.
- 매 SRP (Single Responsibility Principle) 의 quantitative cousin.
**3. 높은 응집도와 낮은 결합도의 주요 이점**
* **가독성 및 유지보수성 향상:** 각 모듈이 명확한 API와 단일 책임을 갖게 되어 프로그램의 동작을 파악하기 쉬워진다 [6], [7]. 또한 특정 기능을 수정할 때 다른 모듈에 미치는 영향이 국소화되어 부작용 발생을 막을 수 있다 [12], [7], [8].
* **재사용성 극대화(DRY 원칙):** 특정 역할에 대해 타 모듈과 독립된 코드는 현재 시스템뿐만 아니라 다른 프로젝트에서도 쉽게 재사용할 수 있어 전체적인 개발 비용을 절감한다 [6], [7], [8].
* **테스트 용이성 확보:** 모듈이 다른 모듈에 거의 의존하지 않으므로, 전체 애플리케이션 환경을 구동할 필요 없이 가짜 데이터(Mock, 페이크 등)로 외부 환경을 대체하여 격리된 독립 테스트(단위 테스트)가 가능해진다 [6], [12], [7], [8].
* **동시 개발의 효율성 향상:** 역할과 경계가 명확하게 분리되면, 여러 엔지니어가 서로의 코드에 간섭하지 않고 독립적으로 병렬 개발을 진행할 수 있다 [6], [12].
### 매 Coupling (결합도) — 매 between
- 매 두 module 간 dependency strength.
- 매 Lower = better. 매 한 module 의 변경 의 다른 module 의 영향 의 최소화.
- 매 inter-module knowledge 의 minimization.
**4. 결합도를 낮추기 위한 전략**
* 모듈 간 상호작용을 추상화된 **인터페이스**를 통해 정의하거나, 필요한 객체를 외부에서 주입받는 **의존성 주입(Dependency Injection)**, 직접 호출 대신 간접적으로 통신하는 **이벤트 기반 아키텍처**를 활용하면 결합도를 효과적으로 줄일 수 있다 [10], [13]. 또한 내부 구현을 캡슐화하고 데이터 구조를 단순화하는 것 역시 의존성을 낮추는 주요 전략이다 [13].
### 매 Cohesion 의 7 levels (low → high)
1. **Coincidental** — 매 unrelated, grouped randomly.
2. **Logical** — 매 same category 만 (e.g., all I/O).
3. **Temporal** — 매 same time 의 execution (e.g., init).
4. **Procedural** — 매 same control flow.
5. **Communicational** — 매 same data 의 작업.
6. **Sequential** — 매 output → next input.
7. **Functional** — 매 single well-defined task. **매 best**.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 Coupling 의 6 levels (high → low)
1. **Content** — 매 internal 의 직접 access. **매 worst**.
2. **Common** — 매 global state 공유.
3. **External** — 매 external format 공유.
4. **Control** — 매 flag 로 behavior 제어.
5. **Stamp** — 매 struct 전체 전달 (subset 만 사용).
6. **Data** — 매 primitive parameter 만. **매 best**.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[단일 책임 원칙 (SRP)|단일 책임 원칙 (SRP]], 의존성 주입 (Dependency Injection), [[스파게티 코드 (Spaghetti Code)|스파게티 코드 (Spaghetti Code]]
- **Projects/Contexts:** [[계층화 아키텍처 (Layered Architecture)|계층화 아키텍처 (Layered Architecture]], [[마이크로서비스 아키텍처 (MSA)|마이크로서비스 아키텍처 (MSA]]
- **Contradictions/Notes:** 세밀한 관심사 분리를 통한 결합도 감소와 응집도 증가가 항상 긍정적인 결과만을 가져오는 것은 아닙니다. 과도하게 세밀한 수준으로 모듈을 쪼개고 분리하면, 복잡한 인디렉션(Indirection)이나 잦은 계층 간 데이터 변환 및 통신 비용 증가 등으로 인해 성능 오버헤드가 발생하거나 오히려 전체 시스템의 추적 가능성을 떨어뜨릴 수 있습니다 [14], [15], [16].
## 💻 패턴
---
*Last updated: 2026-04-18*
---
## 🤖 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
### 매 Functional Cohesion 예
```python
# 매 Good — single purpose
class OrderTotalCalculator:
def calculate(self, items: list[OrderItem]) -> Money:
subtotal = sum(item.price * item.qty for item in items)
tax = subtotal * Decimal("0.10")
return Money(subtotal + tax, "USD")
```
## 🤔 의사결정 기준 (Decision Criteria)
### 매 Coincidental Cohesion (anti)
```python
# 매 Bad — utility kitchen sink
class Helpers:
def format_date(self, d): ...
def hash_password(self, pw): ...
def parse_json(self, s): ...
def send_email(self, to): ...
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 매 Data Coupling (best)
```python
# 매 Good — primitive params
def discount(price: Decimal, rate: Decimal) -> Decimal:
return price * (1 - rate)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### 매 Content Coupling (worst)
```python
# 매 Bad — reaching into internals
class A:
def __init__(self):
self._cache = {}
**기본값:**
> *(TODO)*
class B:
def use(self, a: A):
a._cache["secret"] = 1 # 매 violation
```
## ❌ 안티패턴 (Anti-Patterns)
### 매 Stamp → Data 의 refactor
```python
# Before: stamp coupling
def ship(order: Order): # 매 Order 전체 의존
address = order.customer.address
...
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
# After: data coupling
def ship(address: Address):
...
```
### 매 Control Coupling 의 split
```python
# Before
def process(data, mode):
if mode == "A": ...
elif mode == "B": ...
# After
def process_a(data): ...
def process_b(data): ...
```
### 매 Microservice boundary 의 cohesion
```yaml
# 매 Bounded context 별 service
services:
order-service: # 매 functional cohesion
responsibility: order lifecycle
payment-service:
responsibility: payment processing
shipping-service:
responsibility: fulfillment
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 module 의 reason to change 의 multiple | 매 Split — cohesion 향상 |
| 매 cross-module call 의 빈번 | 매 Merge or 의 facade — coupling 감소 |
| 매 global state 의존 | 매 Inject as dependency |
| 매 flag parameter | 매 Polymorphism / strategy 로 split |
| 매 internal field 의 access | 매 Encapsulation — getter/method |
**기본값**: 매 high cohesion (functional) + 매 low coupling (data) 의 추구.
## 🔗 Graph
- 부모: [[소프트웨어 설계 원칙]] · [[Structured Design]]
- 변형: [[응집도 (Cohesion)]] · [[Connascence]]
- 응용: [[SOLID]] · [[Domain-Driven Design]] · [[Microservices]]
- Adjacent: [[모듈성]] · [[Bounded Context]]
## 🤖 LLM 활용
**언제**: 매 module / class / service boundary 결정 시. 매 refactoring trigger 의 식별.
**언제 X**: 매 single-file script. 매 prototype throwaway code.
## ❌ 안티패턴
- **God class**: 매 모든 의 처리 → 매 low cohesion.
- **Shotgun surgery**: 매 한 변경 의 N module 의 touch → 매 high coupling.
- **Feature envy**: 매 method 의 다른 class 의 data 의 과다 access.
- **Inappropriate intimacy**: 매 두 class 의 internals 의 share.
## 🧪 검증 / 중복
- Verified — Constantine & Yourdon, *Structured Design* (1979); Meilir Page-Jones, *Practical Guide to Structured Systems Design*.
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — cohesion/coupling levels + refactor patterns |