[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,91 +2,139 @@
|
||||
id: wiki-2026-0508-스파게티-코드-spaghetti-code
|
||||
title: 스파게티 코드 (Spaghetti Code)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-9FBF28]
|
||||
aliases: [spaghetti code, tangled code]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [anti-pattern, code-quality, refactoring]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - 스파게티 코드 (Spaghetti Code)"
|
||||
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
|
||||
---
|
||||
|
||||
# [[스파게티 코드 (Spaghetti Code)]]
|
||||
# 스파게티 코드 (Spaghetti Code)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> 스파게티 코드는 알고리즘의 논리를 작성하거나 파악할 때 여러 기능이나 모듈 사이를 빈번하게 뛰어다녀야 하는 복잡하게 얽힌 상태의 코드를 의미합니다. 이는 시스템 내 코드의 응집도(Cohesion)가 낮다는 것을 보여주는 대표적인 신호입니다. 이러한 코드는 실행 흐름을 추적하기 어렵게 만들어 유지보수성과 가독성을 크게 떨어뜨립니다.
|
||||
## 매 한 줄
|
||||
> **"매 control flow 가 noodle 처럼 entangled 되어 trace 불가"**. 매 unstructured GOTO · deeply nested conditions · global state mutation · circular dependency 가 만든 maintenance nightmare. 매 SOLID 위반 의 most visible symptom.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **응집도 저하의 결과물:** 로직의 흐름을 따라가기 위해 이곳저곳의 함수나 모듈 사이를 계속해서 점프해야 한다면, 이는 해당 코드의 응집도가 낮다는 것을 의미하며 소프트웨어 공학에서는 이를 종종 '스파게티 코드'라고 부릅니다 [1-3].
|
||||
- **설계 원칙의 부재:** 스파게티 코드는 프로그램의 각 부분이 서로 다른 기능이나 특정 관심사에만 집중하도록 설계하는 '관심사의 분리([[Separation of Concerns]], SoC)' 원칙이 제대로 지켜지지 않았을 때 나타납니다 [4, 5].
|
||||
- **해결 및 개선 방향:** 스파게티 코드를 방지하고 해결하기 위해서는 밀접하게 관련되지 않은 기능들을 분리하고, 동일하고 고유한 목적을 제공하는 기능들끼리 논리적으로 그룹화하여 높은 응집도(High Cohesion)를 확보해야 합니다 [6, 7].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 증상
|
||||
- **Tangled control flow**: 함수 한 개가 500+ lines, nested if 5+.
|
||||
- **Global state**: any 함수 가 any 변수 mutate.
|
||||
- **Circular dep**: A→B→C→A.
|
||||
- **Magic numbers/strings**: meaning unclear.
|
||||
- **Copy-paste**: same logic in 7 places.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[응집도 (Cohesion)]], [[관심사의 분리 (Separation of Concerns)]]
|
||||
- **Projects/Contexts:** 소스에 관련 정보가 부족합니다.
|
||||
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다.
|
||||
### 매 원인
|
||||
- Time pressure → "just make it work".
|
||||
- No code review → drift 누적.
|
||||
- Premature optimization → unnecessary complexity.
|
||||
- Lack of architecture → ad-hoc additions.
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-18*
|
||||
### 매 응용 (refactor 전략)
|
||||
1. Extract method · extract class.
|
||||
2. Replace conditional with polymorphism.
|
||||
3. Introduce parameter object.
|
||||
4. Strangler fig migration.
|
||||
|
||||
---
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 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
|
||||
### Before (spaghetti)
|
||||
```typescript
|
||||
function processOrder(o: any) {
|
||||
if (o.type == "A") {
|
||||
if (o.user.isVip) {
|
||||
o.discount = 0.2;
|
||||
if (o.country == "KR") o.tax = 0.1;
|
||||
else if (o.country == "US") o.tax = 0.07;
|
||||
// ... 200 more lines
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### After (refactored)
|
||||
```typescript
|
||||
type Order = { type: OrderType; user: User; country: Country; items: Item[] };
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const discountStrategy: Record<OrderType, (u: User) => number> = {
|
||||
A: u => u.isVip ? 0.2 : 0.05,
|
||||
B: () => 0.1,
|
||||
};
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const taxRate: Record<Country, number> = { KR: 0.1, US: 0.07, JP: 0.08 };
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
function processOrder(o: Order) {
|
||||
const discount = discountStrategy[o.type](o.user);
|
||||
const tax = taxRate[o.country];
|
||||
return finalizePricing(o, discount, tax);
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Replace conditional with polymorphism
|
||||
```typescript
|
||||
abstract class Payment {
|
||||
abstract process(amount: number): Promise<void>;
|
||||
}
|
||||
class CardPayment extends Payment { async process(a: number) { /* card */ } }
|
||||
class CryptoPayment extends Payment { async process(a: number) { /* btc */ } }
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Extract method
|
||||
```typescript
|
||||
// before: 1 huge function
|
||||
// after: 5 small functions, each <20 lines, single responsibility
|
||||
function checkout(cart: Cart) {
|
||||
validateCart(cart);
|
||||
const total = calculateTotal(cart);
|
||||
const tax = applyTax(total, cart.country);
|
||||
return submitPayment(cart.user, total + tax);
|
||||
}
|
||||
```
|
||||
|
||||
### Detect with cyclomatic complexity
|
||||
```bash
|
||||
npx eslint . --rule 'complexity: ["error", 10]'
|
||||
npx code-complexity ./src --max 10
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Function > 50 lines | extract method |
|
||||
| Nested if > 3 | early return / strategy map |
|
||||
| Same logic in 3+ places | DRY (extract function) |
|
||||
| Module circular dep | dependency inversion |
|
||||
| Cyclomatic > 10 | refactor split |
|
||||
|
||||
**기본값**: function 30 lines 미만 · cyclomatic 10 미만 · single responsibility.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[SOLID 원칙]] · [[관심사의 분리 (Separation of Concerns)]]
|
||||
- Adjacent: [[단일 책임 원칙 (SRP)]] · [[기본 타입에의 집착 (Primitive Obsession)]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: legacy code refactor · cyclomatic 감소 제안 · extract method 자동화.
|
||||
**언제 X**: domain semantics 가 unclear → human review 필수.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Big rewrite**: incremental refactor 가 safe.
|
||||
- **Refactor without tests**: regression 보장 없음.
|
||||
- **Premature abstraction**: 2번째 use case 까지 기다림 (rule of three).
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Fowler "Refactoring" · Martin "Clean Code").
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — spaghetti code refactor 패턴 |
|
||||
|
||||
Reference in New Issue
Block a user