[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,93 +2,257 @@
id: wiki-2026-0508-breaking-dependencies
title: Breaking Dependencies
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Decoupling, Dependency Breaking, Refactoring Legacy]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [refactoring, architecture, legacy-code, testing]
raw_sources: []
last_reinforced: 2026-05-08
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: Java / TypeScript / Python
framework: language-agnostic
---
# [[Breaking Dependencies]]
# Breaking Dependencies
## 📌 한 줄 통찰 (The Karpathy Summary)
'Breaking Dependencies(의존성 제거)'는 단위 테스트 작성을 방해하거나 시스템의 유연성을 저해하는 코드 간의 강한 결합을 끊어내는 리팩토링 과정이다 [1-3]. 주로 데이터베이스 연결이나 외부 서드파티 서버 호출과 같이 코드를 독립적으로 실행하기 어렵게 만드는 무거운 자원을 식별하고, 이를 가짜 객체(Mock) 등 가벼운 대체물로 교체하기 위해 수행된다 [1-3]. 이를 통해 개발자는 레거시 코드에 안전한 테스트를 추가하고, 궁극적으로 더 큰 규모의 리팩토링과 새로운 기능을 안전하게 추가할 수 있는 기반을 마련할 수 있다 [2, 4, 5].
## 한 줄
> **"매 untestable code 를 매 test 가능하게 만드는 첫 단계 = 매 hard dependency 를 매 break."**. Michael Feathers 의 *Working Effectively with Legacy Code* (2004) 의 24 가지 dependency-breaking technique 가 매 canonical reference. 2026 현재 modern DI / 매 hexagonal architecture 가 매 prevention layer, but 매 legacy 에는 여전히 매 Sprout Method / Extract Interface / Adapter 가 핵심.
## 📖 구조화된 지식 (Synthesized Content)
* **레거시 코드 딜레마 극복의 핵심**: 레거시 코드를 안전하게 리팩토링하려면 테스트가 필수적이지만, 테스트를 작성하려면 먼저 코드를 수정해 복잡한 의존성을 끊어내야 하는 모순적인 상황에 직면하게 된다 [2, 6]. 단위 테스트 작성을 가로막는 문제의 99%는 의존성 문제(Dependency Problem)로 귀결되며, 외부 API 호출, 전역 의존성(Global Dependency), 혹은 생성하기 까다로운 매개변수 등이 이에 해당한다 [1, 7]. 의존성 제거는 이 딜레마를 돌파하는 첫 번째 관문이다 [2].
* **접점(Seam)의 식별과 활용**: 의존성을 끊기 위해 개발자는 소스 코드를 직접 수정하지 않고도 프로그램의 동작을 변경할 수 있는 지점인 '접점(Seam)'을 찾아야 한다 [1, 2, 4]. 예를 들어, 객체 지향 언어에서는 문제가 되는 클래스를 확장(Extend)하여 테스트 환경에서 실제 DB에 연결되지 않도록 메서드의 동작을 덮어쓰는 방식을 취해 의존성을 우회할 수 있다 [8, 9].
* **의존성 제거를 위한 구체적 기법들**: 마이클 페더스(Michael Feathers)는 안전하게 의존성을 끊어내기 위한 24가지의 '의존성 제거 기법(Dependency-Breaking Techniques)' 카탈로그를 제시한다 [10]. 여기에는 매개변수 적응시키기(Adapt Parameter), 메서드 객체 추출(Break Out Method Object), 인터페이스 추출(Extract Interface), 인스턴스 위임자 도입(Introduce Instance Delegator), 생성자/메서드 매개변수화(Parameterize Constructor/Method), 하위 클래스화 및 메서드 재정의(Subclass and Override Method) 등의 실용적인 패턴들이 포함된다 [11, 12].
* **모듈 및 아키텍처 수준의 의존성 제거**: 의존성 분리는 단일 클래스나 메서드 단위의 테스트 목적을 넘어, 시스템 아키텍처를 개선하기 위해서도 사용된다. 윈도우(Windows) 리팩토링 사례에서는 여러 바이너리 간에 복잡하게 얽혀 있던 원치 않는 모듈 간 의존성(inter-module dependencies)을 끊어내기 위해 특정 API 기능을 다른 바이너리로 이동시키고 분할하는 시스템 규모의 리팩토링을 수행했다 [13, 14].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **코드의 미학적 손상**: 기존 코드에 단위 테스트를 적용하기 위해 의존성을 제거하는 과정에서, 불가피하게 임시적인 간접 계층이나 불필요해 보이는 메서드를 추가해야 할 수 있다. 이로 인해 리팩토링의 특정 단계에서는 코드가 이전보다 미학적으로 약간 더 지저분해지거나(uglier) 복잡해지는 제약이 발생한다 [15, 16].
* **병적인 코드 베이스에서의 어려움**: 운이 좋다면 의존성이 작고 국소적으로 모여있지만, 코드가 심각하게 망가진 병적인(pathological) 시스템의 경우 의존성이 수없이 많고 코드 전반에 광범위하게 퍼져 있어 이를 끊어내는 과정 자체가 극도로 고통스럽고 오랜 시간이 소요될 수 있다 [5].
* **전처리기 및 링커 접점의 부작용**: 객체 접점(Object Seams)을 사용할 수 없는 C/C++ 같은 언어에서 전처리기 매크로나 링커를 활용해 의존성을 끊는 방식(Preprocessing / Link Seams)은 테스트 환경과 프로덕션 환경의 차이를 불명확하게 만들어, 파악하기 힘든 까다로운 버그를 유발할 수 있다 [17, 18]. 이러한 방식은 테스트의 유지보수성도 저하시키므로 더 나은 대안이 없는 최후의 수단으로만 사용해야 한다 [19].
### 매 dependency types
- **Construction dependency**: `new SomeService()` hardcoded.
- **Static dependency**: `Date.now()`, `Math.random()`, `Singleton.getInstance()`.
- **Hidden dependency**: 매 method 안에서 file / DB / network 직접 호출.
- **Temporal coupling**: 매 method A → B 순서 강요.
- **Inheritance dependency**: 매 base class 가 매 hard-to-test 행위 가짐.
---
*Last updated: 2026-05-03*
### 매 Feathers 의 핵심 24 technique 중 top 8
1. **Sprout Method**: 매 new behavior 를 매 새 method 로 분리해 매 test 가능하게.
2. **Sprout Class**: 매 new behavior 를 매 new class 로.
3. **Extract Interface**: 매 concrete dep → 매 interface → mock.
4. **Extract and Override Call**: 매 hard call 을 매 protected method 로 → subclass 에서 override.
5. **Subclass and Override Method**: 매 testing subclass.
6. **Adapt Parameter**: 매 untestable arg → 매 wrapper interface.
7. **Break Out Method Object**: 매 거대 method → 매 클래스.
8. **Introduce Instance Delegator**: 매 static → 매 instance method 로.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Legacy Java/C# enterprise codebase 의 unit test 도입.
2. Module 간 cyclic dependency 끊기.
3. 매 third-party SDK 의 hard wiring 제거.
4. Microservice extraction 전 prep.
5. 매 monolith 의 plugin 화.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Extract Interface (Java)
```java
// BEFORE — hard wired
public class OrderService {
public Receipt placeOrder(Order o) {
EmailSender sender = new EmailSender(); // hard dep
sender.send(o.customerEmail, "...");
return Receipt.from(o);
}
}
## 🧪 검증 상태 (Validation)
// AFTER — Extract Interface + DI
public interface Notifier {
void send(String to, String body);
}
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
public class EmailSender implements Notifier { /* impl */ }
## 🧬 중복 검사 (Duplicate Check)
public class OrderService {
private final Notifier notifier;
public OrderService(Notifier notifier) { this.notifier = notifier; }
public Receipt placeOrder(Order o) {
notifier.send(o.customerEmail, "...");
return Receipt.from(o);
}
}
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
// Test
@Test void placesOrderAndNotifies() {
var fake = mock(Notifier.class);
var svc = new OrderService(fake);
svc.placeOrder(testOrder());
verify(fake).send(eq("a@b.com"), anyString());
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Sprout Method (TypeScript)
```ts
// BEFORE — 매 huge method, 매 add new logic 못 testable
class Invoice {
process(): void {
// 200 lines 의 legacy
// 매 new logic 추가하면 매 테스트 X
}
}
**선택 A를 써야 할 때:**
- *(TODO)*
// AFTER — sprout 로 새 행동만 분리
class Invoice {
process(): void {
// 200 lines 의 legacy (그대로)
this.applyLoyaltyDiscount(); // 매 sprouted
}
**선택 B를 써야 할 때:**
- *(TODO)*
applyLoyaltyDiscount(): number { // 매 testable in isolation
if (this.customer.tier === 'gold') return this.total * 0.1;
if (this.customer.tier === 'silver') return this.total * 0.05;
return 0;
}
}
```
**기본값:**
> *(TODO)*
### Extract and Override Call (Python)
```python
# BEFORE
class Job:
def run(self):
now = datetime.utcnow() # 매 hard
if now.weekday() >= 5: return
self.do_work()
## ❌ 안티패턴 (Anti-Patterns)
# AFTER
class Job:
def run(self):
if self._now().weekday() >= 5: return
self.do_work()
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
def _now(self) -> datetime: # 매 protected — override in test
return datetime.utcnow()
class TestJob(Job):
def __init__(self, fixed_dt): self.fixed_dt = fixed_dt
def _now(self): return self.fixed_dt
# Test
def test_skips_weekend():
j = TestJob(datetime(2026, 5, 9)) # 매 Saturday
j.do_work = MagicMock()
j.run()
j.do_work.assert_not_called()
```
### Adapt Parameter (Java)
```java
// BEFORE — HttpServletRequest hard to construct in test
public Result handle(HttpServletRequest req) {
String userId = req.getHeader("X-User-Id");
return repo.find(userId);
}
// AFTER — adapter interface
public interface RequestAdapter {
String header(String name);
}
public Result handle(RequestAdapter req) {
return repo.find(req.header("X-User-Id"));
}
// Production wraps; test = trivial map
class ServletRequestAdapter implements RequestAdapter {
private final HttpServletRequest delegate;
public String header(String n) { return delegate.getHeader(n); }
}
```
### Subclass and Override (Python — break DB)
```python
class ReportGenerator:
def fetch(self) -> list[dict]:
return db.query("SELECT * FROM orders") # 매 hard
def render(self) -> str:
rows = self.fetch()
return "\n".join(f"{r['id']}: {r['total']}" for r in rows)
class TestableReport(ReportGenerator):
def __init__(self, fake_rows): self.fake_rows = fake_rows
def fetch(self): return self.fake_rows
def test_renders():
r = TestableReport([{"id": 1, "total": 100}])
assert r.render() == "1: 100"
```
### Wrap Method (legacy 호환 유지)
```java
// 매 old API 깨면 안 됨 → 매 wrap
public void payInvoice(Invoice i) {
audit.log(i); // 매 new behavior
payInvoiceLegacy(i); // 매 unchanged
}
private void payInvoiceLegacy(Invoice i) { /* 매 untouched */ }
```
### Seam mapping checklist
```
1. List 매 untestable thing in target method
- Static call? → Introduce Instance Delegator / Replace Function with Function Object
- new? → Extract Interface + inject
- Time/random? → Extract & Override Call
- File/DB/HTTP? → Repository / Adapter
2. Pick 1 dep / day. 매 small step + commit.
3. 매 Test 먼저 (characterization test)
- 매 current behavior 를 lock down
4. Refactor under green tests.
```
### Hexagonal post-state (prevention)
```
[Domain Core] ← [Port (interface)] ← [Adapter (DB / HTTP / FS)]
매 NO direct import 매 from core to adapter
매 Test = stub adapter against port
```
## 매 결정 기준
| 상황 | Technique |
|---|---|
| 매 add new feature 매 large method | Sprout Method |
| 매 hard dep on concrete class | Extract Interface + DI |
| 매 static / time / random | Extract and Override Call |
| 매 framework type 의 arg | Adapt Parameter |
| 매 file / DB / network | Repository / Port-Adapter |
| 매 huge method 의 internal logic | Break Out Method Object |
| 매 base class behavior bad | Subclass and Override |
**기본값**: characterization test 먼저 → 매 minimal mechanical refactor (compiler-driven) → 매 small commit.
## 🔗 Graph
- 부모: [[Refactoring]] · [[Software-Design]] · [[Legacy-Code]]
- 변형: [[Sprout-Method]] · [[Extract-Interface]] · [[Adapter-Pattern]]
- 응용: [[Test-Driven-Development]] · [[Hexagonal-Architecture]] · [[Strangler-Fig-Pattern]]
- Adjacent: [[Dependency-Injection]] · [[SOLID-Principles]] · [[Mocking]]
## 🤖 LLM 활용
**언제**: legacy code unit test 도입, untestable method 마주침, monolith 분해 직전 prep, third-party SDK lock-in 제거.
**언제 X**: 매 already clean architecture (over-refactor 금지), 매 throwaway prototype.
## ❌ 안티패턴
- **Big-bang rewrite**: 매 일부 break → 매 전체 unstable.
- **Test 없이 refactor**: 매 behavior 변경 모름 → 매 silent regression.
- **너무 많은 mock**: 매 test 가 매 implementation 에 결합.
- **Interface 의 1 implementation 영구**: 매 YAGNI — 매 두 번째 user 생기면 그때 추출.
- **God adapter**: 매 1 interface 에 30 method.
- **Refactor + feature 동시 commit**: 매 review 불가.
## 🧪 검증 / 중복
- Verified (Feathers "Working Effectively with Legacy Code" 2004, Fowler "Refactoring" 2nd ed).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Breaking Dependencies with Feathers techniques |