[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,101 +2,194 @@
|
||||
id: wiki-2026-0508-sprout-wrap-techniques-스프라우트-랩-기
|
||||
title: "Sprout & Wrap Techniques (스프라우트 & 랩 기법)"
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [Sprout and Wrap, Wrap Method, Wrap Class, 스프라우트 랩]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [refactoring, legacy-code, michael-feathers]
|
||||
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
|
||||
framework: junit
|
||||
---
|
||||
|
||||
# [[Sprout & Wrap Techniques (스프라우트 & 랩 기법)]]
|
||||
# Sprout & Wrap Techniques (스프라우트 & 랩 기법)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
스프라우트(Sprout)와 랩(Wrap) 기법은 테스트가 부족하고 당장 전면적인 리팩토링을 수행할 시간이 없는 레거시 시스템에 새로운 코드를 안전하게 추가하기 위해 사용하는 방법이다 [1]. 기존의 방대한 코드를 직접 수정하는 것을 최소화하여 새로운 버그를 도입할 위험을 줄이면서도, 새롭게 추가되는 로직에 대해서는 격리된 상태로 단위 테스트를 작성할 수 있게 해준다 [2, 3].
|
||||
## 매 한 줄
|
||||
> **"매 legacy code 의 직접 수정 X — 매 sprout 의 옆에 새 method/class 의 추가, 매 wrap 의 기존 caller 의 둘러쌈"**. Michael Feathers, *Working Effectively with Legacy Code* (2004) 의 4 paired 기법: Sprout Method, Sprout Class, Wrap Method, Wrap Class.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
레거시 코드 베이스는 기존 코드 덩어리가 새로운 코드를 계속 끌어들이는 중력과 같은 힘을 가지는 경우가 많아, 수천 줄짜리 클래스에 불과 몇 줄의 로직을 무분별하게 덧붙이는 결과를 낳기 쉽다 [1]. 테스트를 작성하고 구조를 개선할 시간이 절대적으로 부족한 까다로운 상황에서 다음 두 가지 기법을 활용할 수 있다 [1].
|
||||
## 매 핵심
|
||||
|
||||
* **스프라우트 기법 (Sprout Technique)**
|
||||
* 기존의 거대한 메서드를 직접 건드리는 대신, 새롭게 추가해야 할 로직을 아예 다른 곳(새로운 메서드나 클래스 등)에 분리하여 작성하는 방식이다 [2, 3].
|
||||
* 새로 작성된 코드는 격리되어 있으므로 쉽게 단위 테스트를 수행할 수 있다 [2, 3].
|
||||
* 테스트가 완료된 후, 기존 레거시 코드 내의 적절한 삽입 지점(insertion point)에서 이 새로운 코드를 호출하도록 연결한다 [2, 3].
|
||||
### 매 4 techniques
|
||||
- **Sprout Method**: 매 새 method 의 옆에 grow, 매 caller 의 1줄 add.
|
||||
- **Sprout Class**: 매 새 class 의 grow, 매 caller 의 instantiate + delegate.
|
||||
- **Wrap Method**: 매 기존 method rename → 매 same name 의 new method 의 둘러쌈 (before/after logic).
|
||||
- **Wrap Class**: 매 decorator/proxy 의 wrap (cross-cutting: logging, auth).
|
||||
|
||||
* **랩 기법 (Wrap Technique)**
|
||||
* 새롭게 추가해야 할 변경 사항이 기존 코드의 실행 전이나 후에 발생해야 할 때 사용하는 기법이다 [4].
|
||||
* 우선 변경하고자 하는 기존 메서드의 이름을 다른 것으로 바꾼다 [4].
|
||||
* 그리고 원래의 이름과 시그니처를 가진 새로운 메서드를 생성한다 [4].
|
||||
* 이 새로운 메서드 내부에서 이름이 바뀐 예전 메서드를 호출하고, 그 앞이나 뒤에 테스트가 가능한 새로운 로직을 추가하여 감싸는(Wrap) 형태를 취한다 [4].
|
||||
* 이 방식을 통해 옛 메서드는 테스트 시에 프로그램의 동작을 변경할 수 있는 접점(Seam)의 역할을 하게 된다 [5].
|
||||
### 매 Sprout vs Wrap
|
||||
- **Sprout**: 매 add new logic to existing operation.
|
||||
- **Wrap**: 매 add cross-cutting (before/after) to existing operation 의 callers.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
* **근본적인 해결책의 부재:** 스프라우트와 랩 기법은 레거시 코드를 다루는 데 있어 매우 유용한 도구이지만, 이들이 이상적인 해결책은 아니며 나름의 함정(pitfalls)을 가지고 있다 [5].
|
||||
* **코드 품질 개선의 한계:** 이 기법들은 근본적으로 리팩토링이나 테스트 작성을 위한 충분한 시간이 없을 때 기존 코드의 악화를 막고 새 코드를 안전하게 넣기 위해 사용하는 임시방편에 가깝다 [1]. 따라서 지속적으로 이러한 기법에만 의존할 경우, 기존에 존재하는 거대하고 구조가 엉망인 코드 자체의 기술 부채는 그대로 남게 된다 [1, 3].
|
||||
### 매 응용
|
||||
1. Add validation before legacy save.
|
||||
2. Add audit logging across all calls.
|
||||
3. Add caching layer transparently.
|
||||
4. Add feature flag toggle.
|
||||
|
||||
---
|
||||
*Last updated: 2026-05-03*
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### Sprout Method
|
||||
```java
|
||||
public void process(Order o) {
|
||||
// legacy untouched
|
||||
repo.save(o);
|
||||
notifyCustomer(o); // sprouted
|
||||
}
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(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
|
||||
void notifyCustomer(Order o) { // tested
|
||||
email.send(o.customer(), template(o));
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Sprout Class — when sprout method 의 not enough
|
||||
```java
|
||||
// Original legacy class — touch minimally
|
||||
public class OrderProcessor {
|
||||
public void process(Order o) {
|
||||
repo.save(o);
|
||||
new OrderNotifier(email, sms).notifyAll(o); // sprouted class
|
||||
}
|
||||
}
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// New, fully tested
|
||||
public class OrderNotifier {
|
||||
private final EmailService email;
|
||||
private final SmsService sms;
|
||||
public OrderNotifier(EmailService e, SmsService s) { this.email = e; this.sms = s; }
|
||||
public void notifyAll(Order o) {
|
||||
email.send(o.customer().email(), "thanks");
|
||||
if (o.customer().smsOptIn()) sms.send(o.customer().phone(), "order placed");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Wrap Method — rename + intercept
|
||||
```java
|
||||
public class Pay {
|
||||
// Step 1: rename original to *Internal
|
||||
private void payInternal(Order o) {
|
||||
gateway.charge(o.amount());
|
||||
}
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
// Step 2: new method with same original name
|
||||
public void pay(Order o) {
|
||||
audit.log("pay.start", o.id()); // before
|
||||
payInternal(o); // delegate
|
||||
audit.log("pay.end", o.id()); // after
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Wrap Class — Decorator
|
||||
```java
|
||||
public interface PaymentGateway { void charge(long amount); }
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
public class StripeGateway implements PaymentGateway { /* legacy untouched */ }
|
||||
|
||||
public class LoggingGateway implements PaymentGateway {
|
||||
private final PaymentGateway inner;
|
||||
private final Logger log;
|
||||
public LoggingGateway(PaymentGateway inner, Logger log) {
|
||||
this.inner = inner; this.log = log;
|
||||
}
|
||||
@Override public void charge(long amount) {
|
||||
log.info("charge.start amount={}", amount);
|
||||
try { inner.charge(amount); }
|
||||
finally { log.info("charge.end"); }
|
||||
}
|
||||
}
|
||||
|
||||
// Wire-up: clients see PaymentGateway, get wrapped version
|
||||
PaymentGateway gw = new LoggingGateway(new StripeGateway(), log);
|
||||
```
|
||||
|
||||
### Wrap Class for caching
|
||||
```java
|
||||
public class CachingRepo implements OrderRepository {
|
||||
private final OrderRepository inner;
|
||||
private final Map<Long, Order> cache = new ConcurrentHashMap<>();
|
||||
public CachingRepo(OrderRepository inner) { this.inner = inner; }
|
||||
public Order findById(long id) {
|
||||
return cache.computeIfAbsent(id, inner::findById);
|
||||
}
|
||||
public Order save(Order o) {
|
||||
var saved = inner.save(o);
|
||||
cache.put(saved.id(), saved);
|
||||
return saved;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Python — wrap with closure
|
||||
```python
|
||||
def wrap_with_audit(fn, audit):
|
||||
def wrapped(*a, **kw):
|
||||
audit.log(f"{fn.__name__}.start")
|
||||
try: return fn(*a, **kw)
|
||||
finally: audit.log(f"{fn.__name__}.end")
|
||||
return wrapped
|
||||
|
||||
pay = wrap_with_audit(legacy_pay, audit)
|
||||
```
|
||||
|
||||
### Sprout 의 test (TDD first)
|
||||
```java
|
||||
@Test
|
||||
void notifyCustomer_priorityOrder_sendsPriorityTemplate() {
|
||||
var o = new Order(customer, true);
|
||||
new OrderProcessor(repo, emailMock, smsMock).notifyCustomer(o);
|
||||
verify(emailMock).send(customer.email(), "priority-thanks");
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Add small new logic to legacy method | **Sprout Method** |
|
||||
| New logic 의 large/independent | **Sprout Class** |
|
||||
| Add before/after to specific method | **Wrap Method** |
|
||||
| Cross-cutting (logging, cache, auth) across many callers | **Wrap Class** (decorator) |
|
||||
| Legacy call sites 의 모두 update 의 가능 | Direct refactor 의 OK |
|
||||
|
||||
**기본값**: 매 legacy add → Sprout. 매 cross-cutting → Wrap Class.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Working Effectively with Legacy Code]] · [[Refactoring]]
|
||||
- 변형: [[Sprout Method (스프라우트 메서드)]] · [[Decorator Pattern]]
|
||||
- 응용: [[Legacy Code Modernization]] · [[Strangler Fig Pattern]]
|
||||
- Adjacent: [[Adapter Pattern]] · [[Proxy Pattern]] · [[Aspect-Oriented Programming]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 untested legacy code 의 modification 필요; 매 cross-cutting concern 의 add.
|
||||
**언제 X**: 매 codebase 의 well-tested — 매 직접 refactor 의 cleaner.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Wrap without rename**: 매 infinite recursion.
|
||||
- **Sprout class 의 1-method-only forever**: 매 결국 dead weight — 매 collapse 의 검토.
|
||||
- **Wrap class 의 not used by all callers**: 매 inconsistent behavior — DI 의 enforce.
|
||||
- **No tests on sprouted/wrapped code**: 매 entire technique 의 point 의 lost.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Feathers, *WELC* ch.6–7, 2004; Fowler refactoring catalog).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full Sprout & Wrap quartet with Java/Python patterns |
|
||||
|
||||
Reference in New Issue
Block a user