[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,98 +2,171 @@
|
||||
id: wiki-2026-0508-object-seam-객체-접점
|
||||
title: Object Seam (객체 접점)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [Object Seam, OO Seam, Polymorphic Seam]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [legacy-code, refactoring, testability, seams, oop]
|
||||
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-mockito
|
||||
---
|
||||
|
||||
# [[Object Seam (객체 접점)]]
|
||||
# Object Seam (객체 접점)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
객체 접점(Object Seam)은 소스 코드를 직접 수정하지 않고도 프로그램의 동작을 변경하거나 대체할 수 있는 코드 내의 특정 지점을 의미한다 [1-3]. 객체지향 프로그래밍 언어에서 활용할 수 있는 가장 명시적이고 유용한 접점 유형으로, 다형성(Polymorphism)이나 상속을 이용하여 실제 실행되는 객체나 메서드를 외부에서 제어할 수 있게 해준다 [4, 5]. 레거시 시스템을 리팩토링할 때 기존 의존성을 끊어내고 가짜 객체(Mock)를 주입하여 안전한 테스트 환경을 확보하는 핵심 수단으로 사용된다 [1, 3, 6].
|
||||
## 매 한 줄
|
||||
> **"매 OO 언어에서 다른 코드 변경 없이 동작을 바꿀 수 있는 분기점 — 매 polymorphism이 enabling point."**. Michael Feathers의 *Working Effectively with Legacy Code* (2004) 에서 정의된 3개 seam (preprocessing, link, object) 중 가장 강력. 2026 현재 mock framework · DI container의 핵심 메커니즘.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **접점(Seam)과 활성화 지점(Enabling Point)의 개념**
|
||||
접점은 코드를 직접 편집하지 않고도 해당 위치에서의 동작을 바꿀 수 있는 곳을 뜻하며, 모든 접점에는 어떤 동작을 사용할지 결정할 수 있는 '활성화 지점(Enabling Point)'이 존재한다 [7]. 객체 접점에서는 주로 메서드의 매개변수 목록이나 객체를 생성하는 지점이 활성화 지점 역할을 한다 [8, 9].
|
||||
* **객체 접점의 작동 원리와 식별**
|
||||
객체지향 프로그램에서는 메서드 호출이 실제로 어떤 메서드의 실행으로 이어질지 고정되어 있지 않다 [4, 10]. 예를 들어 `cell.Recalculate();`라는 코드는 `cell`이 어떤 인스턴스인지에 따라 다르게 동작한다 [10]. 주변 코드를 바꾸지 않고 이 호출의 대상을 바꿀 수 있다면 그것이 바로 객체 접점이다 [10]. 반대로, 메서드 내부에서 직접 특정 클래스의 인스턴스를 생성하고 바로 사용하는 경우에는 코드를 수정하지 않고는 대상 객체를 바꿀 수 없으므로 접점이 아니다 [11].
|
||||
* **테스트 격리를 위한 객체 접점 생성 기법**
|
||||
* **매개변수화:** 내부에서 직접 생성하던 객체를 매개변수로 전달받도록(`buildMartSheet(Cell cell)`) 수정하면, 호출 시 테스트용 객체를 넘겨줄 수 있는 접점이 형성된다 [12].
|
||||
* **상속과 오버라이드(Override):** 외부 데이터베이스 연결이나 API를 호출하는 문제가 되는 클래스가 있다면, 이를 상속받는 테스트용 하위 클래스를 만들어 해당 메서드를 오버라이드하거나 가짜 객체를 주입하도록 코드를 비틀 수 있다 [1, 3, 13].
|
||||
* **정적(Static) 메서드 변환:** 정적 메서드를 호출하는 부분은 본래 객체 접점이 아니지만, `static` 키워드를 제거하고 `protected` 등의 접근 제어자로 바꾸어 가상(virtual) 메서드처럼 만들면 테스트 시 하위 클래스에서 오버라이드하여 접점화할 수 있다 [14, 15].
|
||||
* **객체지향 환경에서의 권장성**
|
||||
객체 접점은 객체지향 언어에서 가장 권장되는 접근법이다 [5]. C나 C++에서 사용하는 전처리(Preprocessing) 접점이나 링크(Link) 접점도 존재하지만, 객체 접점이 훨씬 명시적이며 이에 의존하는 테스트가 유지보수하기 더 쉽기 때문이다 [5].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
* **우회(Indirection)로 인한 구조적 부자연스러움:** 기존 코드를 건드리지 않고 동작을 변경할 수 있게 하려면 결국 활성화 지점을 만들기 위해 코드 구조를 약간 비틀거나 간접화(Indirection)해야 한다 [15, 16]. 정적 메서드를 인스턴스 메서드로 바꾸거나 하위 클래스를 억지로 만드는 등의 과정이 다소 간접적이고 부자연스럽게 느껴질 수 있다 [15].
|
||||
* **레거시 환경에서의 현실적 타협:** 마음에 들지 않는 의존성을 소스 코드에서 직접 삭제하거나 통째로 고치고 싶을 수 있지만, 테스트가 완비되지 않은 엉망인 레거시 코드에서는 그 자체로 거대한 위험을 초래한다 [15]. 따라서 이상적이고 완벽한 설계로 한 번에 가려고 하기보다는, 다소 우회적일지라도 객체 접점을 이용해 테스트를 안전하게 배치할 수 있을 정도로만 코드를 최소한으로 타협하고 수정하는 것이 훨씬 바람직하다 [3, 15].
|
||||
### 매 3 seam types
|
||||
- **Preprocessing seam**: C/C++ macro 치환 — enabling point는 build flag.
|
||||
- **Link seam**: linker가 symbol을 binding — enabling point는 link order.
|
||||
- **Object seam**: virtual dispatch — enabling point는 object instantiation.
|
||||
|
||||
---
|
||||
*Last updated: 2026-05-03*
|
||||
### 매 Object Seam 작동 원리
|
||||
- Polymorphic type (interface, abstract class, base class with virtual)
|
||||
- Caller가 abstract type 사용
|
||||
- Subtype 선택은 외부 (constructor, factory, DI container)
|
||||
- 매 단순 if/else 분기 vs polymorphism 분기
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. Test에서 real DB → in-memory fake 교체.
|
||||
2. HTTP client → mock으로 network 차단.
|
||||
3. Strategy pattern으로 algorithm swap.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Java — interface seam
|
||||
```java
|
||||
public interface PaymentGateway {
|
||||
PaymentResult charge(Money amount, Card card);
|
||||
}
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
public class CheckoutService {
|
||||
private final PaymentGateway gateway; // ← seam
|
||||
public CheckoutService(PaymentGateway g) { this.gateway = g; }
|
||||
public Order checkout(Cart cart, Card card) {
|
||||
var result = gateway.charge(cart.total(), card);
|
||||
return result.success() ? Order.confirmed(cart) : Order.failed();
|
||||
}
|
||||
}
|
||||
|
||||
- **정보 상태:** 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
|
||||
// Test: enabling point = constructor arg
|
||||
@Test void rejects_failed_payment() {
|
||||
var fake = (amount, card) -> PaymentResult.failed("declined");
|
||||
var svc = new CheckoutService(fake);
|
||||
assertEquals(OrderStatus.FAILED, svc.checkout(cart, card).status());
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### TypeScript — class hierarchy seam
|
||||
```typescript
|
||||
abstract class Notifier {
|
||||
abstract send(msg: string): Promise<void>;
|
||||
}
|
||||
class EmailNotifier extends Notifier { /* SMTP */ }
|
||||
class TestNotifier extends Notifier {
|
||||
sent: string[] = [];
|
||||
async send(msg: string) { this.sent.push(msg); }
|
||||
}
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// Production: new EmailNotifier()
|
||||
// Test: new TestNotifier() — same caller
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### C++ — virtual function seam
|
||||
```cpp
|
||||
class Clock {
|
||||
public:
|
||||
virtual ~Clock() = default;
|
||||
virtual std::chrono::system_clock::time_point now() const = 0;
|
||||
};
|
||||
class SystemClock : public Clock {
|
||||
auto now() const override { return std::chrono::system_clock::now(); }
|
||||
};
|
||||
class FakeClock : public Clock {
|
||||
std::chrono::system_clock::time_point t_;
|
||||
public:
|
||||
void advance(std::chrono::seconds s) { t_ += s; }
|
||||
auto now() const override { return t_; }
|
||||
};
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Introducing seam to legacy code (Extract Interface)
|
||||
```java
|
||||
// Before: hard dependency on concrete class
|
||||
public class Report {
|
||||
public void generate() {
|
||||
var db = new MySQLConnection(); // ← no seam
|
||||
// ...
|
||||
}
|
||||
}
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
// After: introduced object seam
|
||||
public class Report {
|
||||
private final Database db;
|
||||
public Report(Database db) { this.db = db; }
|
||||
public void generate() { /* uses db */ }
|
||||
}
|
||||
public interface Database { ResultSet query(String sql); }
|
||||
public class MySQLConnection implements Database { /* ... */ }
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Testing legacy code with subclass-and-override
|
||||
```java
|
||||
public class LegacyService {
|
||||
public Report run() {
|
||||
var data = fetchData(); // ← protected, override in test
|
||||
return process(data);
|
||||
}
|
||||
protected Data fetchData() { /* real network */ }
|
||||
}
|
||||
// Test
|
||||
class TestableService extends LegacyService {
|
||||
@Override protected Data fetchData() { return Data.fixture(); }
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| New code, OO language | Constructor injection + interface |
|
||||
| Legacy class, can't refactor much | Extract Interface + DI |
|
||||
| Sealed legacy class | Subclass and Override Method |
|
||||
| C/C++ no virtual overhead | Link seam (selective compilation) |
|
||||
| Functional language | Higher-order function = seam |
|
||||
|
||||
**기본값**: interface + constructor injection — 매 가장 explicit · testable.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Seam (접점)]] · [[Seams (이음새)]]
|
||||
- 변형: [[Link Seam (링크 접점)]] · [[Preprocessing Seam (전처리 접점)]]
|
||||
- 응용: [[Dependency Injection (의존성 주입)]] · [[Mock Objects (가짜 객체)]] · [[Test Doubles (테스트 대역)]]
|
||||
- Adjacent: [[Polymorphism (다형성)]] · [[Strategy_Pattern]] · [[Hexagonal_Architecture_Ports_and_Adapters]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: legacy code testability 도입, mock framework 설계, plug-in architecture, strategy swap.
|
||||
**언제 X**: pure functional code (no objects), one-shot script, performance-critical hot loop (virtual call overhead).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Concrete class 직접 new**: 매 seam 없음 — Test 어려움.
|
||||
- **`static` method 의존**: 매 polymorphism 불가 — wrap with instance method.
|
||||
- **Final/sealed class without interface**: 매 subclass override seam도 막음.
|
||||
- **Service Locator** (anti): 매 hidden dependency — explicit constructor injection 권장.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Feathers *WELC* 2004, Fowler *Refactoring* 2nd ed., Meszaros *xUnit Patterns* 2007).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Object seam definition + 3 language patterns |
|
||||
|
||||
Reference in New Issue
Block a user