Files
2nd/10_Wiki/Topics/Domain_Programming/Programming & Language/스파게티 코드 (Spaghetti Code).md
T
Antigravity Agent c24165b8bc refactor(topics): 멀티 에이전트용 지식 재편 — _Common(공통 기본기) + Domain_* 구조
에이전트 8종(대화형/프로그래머 C·S/디자이너/설계자/기획자/QA/PD/PM)에게
[공통 기본 능력 + 롤별 Specialty] 2층으로 지식을 주입하기 위한 재분류.
문서 내용·포맷은 무수정, 폴더 이동만 (6,372개 문서 수 보존 확인).

- Topic_Programming → Domain_Programming (내부 구조 보존)
- Topic_Graphic → Domain_Design
- Topic_Business → Domain_Product
- Topic_General → Domain_General
- _Common 신설: Math(구 Topic_Math_Specialty), Reasoning(구 General/From_Thinking & Reasoning),
  Reasoning_Creativity(구 General/From_창의성), Communication(Poetic_Blog_Writing + From_writing)
- 타 도메인의 From_* 폴더는 유지 (출처 표기일 뿐, 이미 도메인에 맞게 분류된 문서)
- 빈 폴더 정리 (memory/procedures)
- 에이전트→폴더 매핑은 workspace의 .astra/agent-knowledge-map.json (9개 에이전트)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 11:05:56 +09:00

4.0 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-스파게티-코드-spaghetti-code 스파게티 코드 (Spaghetti Code) 10_Wiki/Topics verified self
spaghetti code
tangled code
none A 0.95 applied
anti-pattern
code-quality
refactoring
2026-05-10 pending
language framework
any any

스파게티 코드 (Spaghetti Code)

매 한 줄

"매 control flow 가 noodle 처럼 entangled 되어 trace 불가". 매 unstructured GOTO · deeply nested conditions · global state mutation · circular dependency 가 만든 maintenance nightmare. 매 SOLID 위반 의 most visible symptom.

매 핵심

매 증상

  • 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.

매 원인

  • Time pressure → "just make it work".
  • No code review → drift 누적.
  • Premature optimization → unnecessary complexity.
  • Lack of architecture → ad-hoc additions.

매 응용 (refactor 전략)

  1. Extract method · extract class.
  2. Replace conditional with polymorphism.
  3. Introduce parameter object.
  4. Strangler fig migration.

💻 패턴

Before (spaghetti)

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
    }
  }
}

After (refactored)

type Order = { type: OrderType; user: User; country: Country; items: Item[] };

const discountStrategy: Record<OrderType, (u: User) => number> = {
  A: u => u.isVip ? 0.2 : 0.05,
  B: () => 0.1,
};

const taxRate: Record<Country, number> = { KR: 0.1, US: 0.07, JP: 0.08 };

function processOrder(o: Order) {
  const discount = discountStrategy[o.type](o.user);
  const tax = taxRate[o.country];
  return finalizePricing(o, discount, tax);
}

Replace conditional with polymorphism

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 */ } }

Extract method

// 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

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 패턴