[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,96 +2,173 @@
|
||||
id: wiki-2026-0508-pull-up-method
|
||||
title: Pull Up Method
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [Pull Up Refactoring, Method Hoisting]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [refactoring, oop, inheritance]
|
||||
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: refactoring
|
||||
---
|
||||
|
||||
# [[Pull Up Method]]
|
||||
# Pull Up Method
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
Pull Up Method(메서드 올리기)는 형제 하위 클래스(sibling classes)들에 중복으로 존재하는 동일한 메서드를 부모 클래스(superclass)로 끌어올려 중앙집중화하는 리팩토링 기법이다 [1], [2]. 이 기법은 코드 중복을 제거하여 불필요한 노력을 줄이고, 한쪽 메서드만 수정되어 발생할 수 있는 잠재적 버그를 예방하기 위해 사용된다 [1], [3]. 자식 클래스들이 완전히 동일한 본문을 가진 메서드를 공유할 때 가장 직관적으로 적용할 수 있는 일반화(Generalization) 리팩토링 중 하나이다 [4], [5].
|
||||
## 매 한 줄
|
||||
> **"매 duplicated method 매 sibling subclasses 안 — 매 superclass 로 hoist"**. Fowler의 Refactoring (1999, 2nd ed 2018) 매 catalog item. 매 Extract Superclass / Replace Inheritance with Delegation 와 매 짝.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **적용 동기:** 여러 하위 클래스에서 동일한 동작을 수행하는 두 메서드가 그대로 방치될 경우 향후 버그의 온상이 될 수 있다 [3]. 중복된 메서드가 존재하면 코드 수정 시 한쪽만 변경하고 다른 하나는 변경하지 않고 누락할 위험이 있기 때문에 이를 슈퍼클래스로 올려 단일화해야 한다 [3]. 또한, 하위 클래스의 메서드가 상위 클래스의 메서드를 재정의(override)하면서 실제로는 동일한 작업을 수행하는 특수한 경우에도 이 기법이 필요하다 [6].
|
||||
* **실행 절차:**
|
||||
1. 형제 클래스 간의 메서드를 검사하여 두 메서드의 구현이 정말로 완벽하게 동일한지 확인 및 분석한다 [1], [7]. 만약 시그니처가 다르다면 슈퍼클래스에서 사용할 형태로 시그니처를 일치시킨다 [7].
|
||||
2. 부모 클래스에 새로운 메서드를 생성한 후, 중복 메서드의 본문을 복사하여 붙여넣고 조정한다 [1], [7]. 필요하다면 가시성(visibility)을 `protected`로 변경한다 [1].
|
||||
3. 하위 클래스들에서 중복된 메서드 구현을 삭제하고 코드를 컴파일 및 테스트한다 [1], [8].
|
||||
4. 오직 슈퍼클래스의 메서드만 남을 때까지 모든 하위 클래스에서 해당 메서드를 삭제하고 테스트하는 과정을 반복한다 [8].
|
||||
* **관련 기법의 활용:** 두 메서드가 비슷하지만 완전히 같지 않은 경우에는 '메서드 올리기'를 바로 적용할 수 없다 [7]. 이럴 때는 먼저 '알고리즘 전환(Substitute Algorithm)'이나 '템플릿 메서드 형성(Form Template Method)'을 사용하여 차이점을 분리하고 공통점을 추출하는 작업이 선행되어야 한다 [7].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
* **하위 클래스 종속성 문제:** '메서드 올리기'를 적용할 때 가장 다루기 까다로운 부분은 끌어올리려는 메서드의 본문이 슈퍼클래스에는 없고 하위 클래스에만 존재하는 기능(메서드나 필드)을 참조하는 경우이다 [6].
|
||||
* **하위 메서드 참조 시 제약:** 끌어올린 메서드가 하위 클래스에만 존재하는 다른 메서드를 호출하는 경우, 해당 메서드도 함께 일반화하여 끌어올리거나 슈퍼클래스에 추상 메서드(abstract method)로 선언해야만 정상적으로 컴파일되고 동작할 수 있다 [6], [8]. 이를 해결하기 위해 메서드의 시그니처를 변경하거나 별도의 위임(delegating) 메서드를 만들어야 하는 복잡함이 수반될 수 있다 [6].
|
||||
* **하위 필드 참조 시 제약:** 끌어올린 메서드가 하위 클래스의 특정 필드를 사용하는 경우라면, '필드 올리기(Pull Up Field)'나 '필드 자가 캡슐화(Self Encapsulate Field)'를 적용해야 하며, 슈퍼클래스에 추상화된 getter 메서드를 선언하여 접근해야 하는 구조적 제약이 따른다 [8].
|
||||
### 매 trigger
|
||||
- 매 두 개 이상 sibling subclass 가 매 identical (or near-identical) method body 보유.
|
||||
- 매 fields 도 같이 pull up 가능 — `Pull Up Field`.
|
||||
- 매 constructor body 도 — `Pull Up Constructor Body`.
|
||||
|
||||
---
|
||||
*Last updated: 2026-05-03*
|
||||
### 매 mechanics
|
||||
- 매 step 1: 매 method bodies 매 inspect — 매 truly identical 인지.
|
||||
- 매 step 2: 매 differences 매 parameterize — 매 identical 로 만들기.
|
||||
- 매 step 3: 매 superclass 매 method 작성, 매 subclasses 매 method 삭제.
|
||||
- 매 step 4: 매 test — 매 polymorphic dispatch 매 correct 인지.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. ORM entity hierarchy — 매 `BaseEntity` 매 `id`, `createdAt` pull up.
|
||||
2. UI component class hierarchy — 매 common rendering logic.
|
||||
3. Service layer — 매 audit/logging method pull up.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Java — Pull Up Method
|
||||
```java
|
||||
// Before
|
||||
class Salesman extends Employee {
|
||||
String getName() { return name; }
|
||||
}
|
||||
class Engineer extends Employee {
|
||||
String getName() { return name; }
|
||||
}
|
||||
|
||||
## 🧪 검증 상태 (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
|
||||
// After
|
||||
class Employee {
|
||||
protected String name;
|
||||
String getName() { return name; }
|
||||
}
|
||||
class Salesman extends Employee {}
|
||||
class Engineer extends Employee {}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Pull Up Field
|
||||
```java
|
||||
// Before
|
||||
class Salesman extends Employee {
|
||||
private String name;
|
||||
}
|
||||
class Engineer extends Employee {
|
||||
private String name;
|
||||
}
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// After
|
||||
class Employee {
|
||||
protected String name;
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Pull Up Constructor Body
|
||||
```java
|
||||
class Employee {
|
||||
protected String name;
|
||||
protected Employee(String name) { this.name = name; }
|
||||
}
|
||||
class Manager extends Employee {
|
||||
private int grade;
|
||||
Manager(String name, int grade) {
|
||||
super(name); // pulled up
|
||||
this.grade = grade;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Python — pull up via ABC
|
||||
```python
|
||||
from abc import ABC
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
class Shape(ABC):
|
||||
def describe(self) -> str:
|
||||
return f"Shape with area {self.area():.2f}"
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
class Circle(Shape):
|
||||
def __init__(self, r): self.r = r
|
||||
def area(self): return 3.14159 * self.r ** 2
|
||||
|
||||
class Square(Shape):
|
||||
def __init__(self, s): self.s = s
|
||||
def area(self): return self.s ** 2
|
||||
```
|
||||
|
||||
### TypeScript — abstract class
|
||||
```typescript
|
||||
abstract class Animal {
|
||||
constructor(protected name: string) {}
|
||||
describe(): string { // pulled up from Dog/Cat
|
||||
return `${this.name} is a ${this.constructor.name}`;
|
||||
}
|
||||
abstract makeSound(): string;
|
||||
}
|
||||
class Dog extends Animal { makeSound() { return "Woof"; } }
|
||||
class Cat extends Animal { makeSound() { return "Meow"; } }
|
||||
```
|
||||
|
||||
### Refactoring with parameterization
|
||||
```java
|
||||
// Before — almost identical
|
||||
class A { int charge() { return base * 1.05; } }
|
||||
class B { int charge() { return base * 1.10; } }
|
||||
|
||||
// Step: parameterize
|
||||
class A extends Billing { int charge() { return calc(1.05); } }
|
||||
class B extends Billing { int charge() { return calc(1.10); } }
|
||||
|
||||
// Pull up
|
||||
class Billing { protected int calc(double rate) { return base * rate; } }
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 identical method 매 2+ sibling | Pull Up Method |
|
||||
| 매 similar but different method | Form Template Method 먼저 |
|
||||
| 매 only 1 subclass uses | Don't pull up |
|
||||
| 매 deep inheritance (>3 levels) | Composition 고려 |
|
||||
| 매 LSP 위반 risk | Don't — Extract Class instead |
|
||||
|
||||
**기본값**: 매 2+ siblings 매 identical body — Pull Up. 매 그 외 — composition.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Refactoring]] · [[Inheritance]]
|
||||
- 변형: [[Pull Up Field]] · [[Pull Up Constructor Body]] · [[Push Down Method]]
|
||||
- 응용: [[Extract Superclass]] · [[Form Template Method]]
|
||||
- Adjacent: [[Composition over Inheritance]] · [[Liskov Substitution]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 sibling classes 매 duplication detection — LLM 매 structural similarity 매 잘 detect. 매 IDE refactor (IntelliJ, Rider) 매 mechanical transform 자동.
|
||||
**언제 X**: 매 cross-cutting concern (logging, auth) — Pull Up 대신 매 aspect / decorator.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Forced inheritance**: 매 unrelated classes 매 method 공유 위해 매 fake superclass — composition 사용.
|
||||
- **God superclass**: 매 너무 많이 pull up — base class 가 매 dumping ground 가 됨.
|
||||
- **LSP violation**: 매 pulled-up method 가 매 some subclass 에서 매 invalid — split.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Fowler — Refactoring 2nd ed, 2018, ch 12).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full refactoring catalog entry |
|
||||
|
||||
Reference in New Issue
Block a user