[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,89 +2,263 @@
|
||||
id: wiki-2026-0508-clean-code-principles
|
||||
title: Clean Code Principles
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [CS-CLEAN-CODE-001]
|
||||
aliases: [clean code, SOLID, DRY, KISS, YAGNI, Robert Martin, Uncle Bob, naming, function rules]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [software-engineering, clean-code, srp, dry, kiss, refactoring, maintainability]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [clean-code, solid, dry, kiss, refactoring, software-craftsmanship, naming, code-quality]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
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: language-agnostic
|
||||
framework: any
|
||||
---
|
||||
|
||||
# Clean Code [[Principles|Principles]] (클린 코드 원칙)
|
||||
# Clean Code Principles
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "코드는 컴퓨터가 읽기 위함이 아니라, 미래의 나를 포함한 '다른 인간'이 단번에 의도를 파악할 수 있도록 설계된 고도의 의사소통 수단이다" — 유지보수 효율을 극대화하고 소프트웨어의 부패를 막기 위한 코드 작성의 도덕적/기술적 기준.
|
||||
## 📌 한 줄 통찰
|
||||
> **"매 code 의 communication 의 tool"**. 매 machine 보다 매 future-self / 매 colleague. Robert Martin (Uncle Bob) 의 catalog 가, 매 dogma 의 risk. 매 modern AI 시대 의 maintainability 의 even more critical.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Human-Centric Engineering and Responsibility Separation" — 기계적인 동작 완성을 넘어, 이름 짓기(Naming), 함수 설계, 클래스 구조에서 의미적 명확성과 단일 책임(Single Responsibility)을 관철시키는 패턴.
|
||||
- **핵심 원칙:**
|
||||
- **Meaningful Names:** 변수와 함수명은 존재 이유와 기능을 스스로 설명해야 함.
|
||||
- **Single Responsibility (SRP):** 하나의 함수/클래스는 오직 하나의 일만 수행하고 하나의 변경 이유만 가져야 함.
|
||||
- **DRY (Don't Repeat Yourself):** 중복은 시스템의 복잡도를 높이고 버그의 온상이 됨. 추상화를 통해 제거.
|
||||
- **[[KISS (Keep It Simple, Stupid)|KISS (Keep It Simple, Stupid)]]:** 가장 단순한 해결책이 가장 좋은 해결책임.
|
||||
- **의의:** 기술 부채(Technical Debt)의 누적을 방지하고, 대규모 협업 환경에서 코드 리뷰 비용을 획기적으로 낮추며 시스템의 수명을 연장함.
|
||||
## 매 핵심 principle
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 과거에는 메모리와 성능 최적화를 위해 짧고 암호 같은 코드를 선호했으나, 현대 정책은 하드웨어 자원보다 '개발자의 인지적 자원(Cognitive Resource)'을 훨씬 비싼 자산으로 간주하여 가독성을 최우선 정책으로 삼음.
|
||||
- **정책 변화:** Antigravity 프로젝트는 에이전트가 생성하는 모든 코드에 대해 SOLID 원칙과 클린 코드 가이드라인을 강제 적용하며, 복잡도가 일정 수준 이상인 코드는 자동 리팩토링 루프에 진입시킴.
|
||||
### Naming
|
||||
- **Intention-revealing**: `daysSinceLastLogin` > `d`.
|
||||
- **Searchable**: 매 unique enough.
|
||||
- **Pronounceable**: 매 conversation 의 가능.
|
||||
- **Avoid mental mapping**: `i` 의 single-letter 의 OK 만 매 small loop.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- Software-Architecture-Patterns, Refactoring-Techniques, SOLID-Principles-in-React, [[Technical-Debt|Technical-Debt]]-[[Management|Management]]
|
||||
- **Raw Source:** 00_Raw/Clean Code Principles.md
|
||||
### Function
|
||||
- **Small** (Fowler: <10 line ideal).
|
||||
- **Do one thing**.
|
||||
- **Single level of abstraction**.
|
||||
- **Few argument** (0-3, ideally <2).
|
||||
- **No side effect** (or 매 명시적).
|
||||
- **No flag argument** (boolean → 매 별도 function).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### SOLID (5 principles)
|
||||
1. **S — Single Responsibility**: 매 1 reason to change.
|
||||
2. **O — Open/Closed**: 매 extend 의 OK, 매 modify 의 X.
|
||||
3. **L — Liskov Substitution**: 매 subclass 의 swap 의 OK.
|
||||
4. **I — Interface Segregation**: 매 small + focused interface.
|
||||
5. **D — Dependency Inversion**: 매 abstraction 의 depend, 매 concrete X.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Other
|
||||
- **DRY** (Don't Repeat Yourself).
|
||||
- **KISS** (Keep It Simple, Stupid).
|
||||
- **YAGNI** (You Aren't Gonna Need It).
|
||||
- **POLA** (Principle of Least Astonishment).
|
||||
- **Boy Scout Rule** (better than found).
|
||||
- **Composition over inheritance**.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### 매 critique (Casey Muratori, others)
|
||||
- 매 over-abstraction.
|
||||
- 매 small function 의 maze.
|
||||
- 매 SOLID 의 mechanical 적용 의 bad design.
|
||||
- 매 dogma 의 trap.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
→ 매 principle 의 intent 의 understand. 매 mechanical 적용 X.
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### 매 modern context
|
||||
- 매 AI-generated code 의 review 의 base.
|
||||
- 매 LLM 의 sometimes good naming, 매 sometimes verbose.
|
||||
- 매 comment 의 LLM 의 over-add 의 trim.
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
## 💻 패턴
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### Naming (TS)
|
||||
```ts
|
||||
// ❌ Bad
|
||||
const d = new Date();
|
||||
const ut = users.filter(u => u.lt < d - 30);
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
// ✅ Good
|
||||
const today = new Date();
|
||||
const inactiveUsers = users.filter(u =>
|
||||
u.lastLoginDate < addDays(today, -30)
|
||||
);
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Function size
|
||||
```ts
|
||||
// ❌ Long function
|
||||
function processOrder(order) {
|
||||
// 매 50 line: validate, calculate tax, calculate shipping,
|
||||
// apply discount, save to db, send email, log audit...
|
||||
}
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// ✅ Decomposed
|
||||
function processOrder(order) {
|
||||
validate(order);
|
||||
const total = calculateTotal(order);
|
||||
persist(order, total);
|
||||
notify(order);
|
||||
audit(order);
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### SRP (Single Responsibility)
|
||||
```ts
|
||||
// ❌ Multiple responsibility
|
||||
class User {
|
||||
save() { db.save(this); }
|
||||
sendEmail() { mailer.send(this.email, ...); }
|
||||
hashPassword() { ... }
|
||||
validateInput() { ... }
|
||||
}
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
// ✅ Separated
|
||||
class User { ... data ... }
|
||||
class UserRepository { save(user) { db.save(user); } }
|
||||
class UserMailer { send(user, ...) { mailer.send(user.email, ...); } }
|
||||
class PasswordHasher { hash(plain) { ... } }
|
||||
class UserValidator { validate(input) { ... } }
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### OCP (Open/Closed)
|
||||
```ts
|
||||
// ❌ Modify on each new shape
|
||||
function area(shape) {
|
||||
if (shape.type === 'circle') return Math.PI * shape.r ** 2;
|
||||
if (shape.type === 'square') return shape.side ** 2;
|
||||
// 매 새 shape 의 add → 매 modify
|
||||
}
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
// ✅ Extend (polymorphism)
|
||||
interface Shape { area(): number; }
|
||||
class Circle implements Shape { area() { ... } }
|
||||
class Square implements Shape { area() { ... } }
|
||||
// 매 새 shape 의 add → 매 새 class.
|
||||
```
|
||||
|
||||
### Dependency Inversion
|
||||
```ts
|
||||
// ❌ Concrete dependency
|
||||
class OrderService {
|
||||
private db = new PostgresDatabase();
|
||||
save(order) { this.db.save(order); }
|
||||
}
|
||||
|
||||
// ✅ Abstraction
|
||||
interface Database { save(item): void; }
|
||||
class OrderService {
|
||||
constructor(private db: Database) {}
|
||||
save(order) { this.db.save(order); }
|
||||
}
|
||||
```
|
||||
|
||||
### DRY (carefully)
|
||||
```ts
|
||||
// ❌ Duplicate
|
||||
function calcRetailPrice(p) { return p * 1.1 * 0.95; }
|
||||
function calcWholesalePrice(p) { return p * 1.1 * 0.85; }
|
||||
|
||||
// ✅ Extract
|
||||
function applyTaxAndDiscount(price, discount) {
|
||||
return price * 1.1 * (1 - discount);
|
||||
}
|
||||
|
||||
// ⚠️ But: 매 too eager DRY → premature abstraction.
|
||||
// "Two cases that look similar may have different reasons.
|
||||
// Wait for 3rd duplicate before abstracting."
|
||||
```
|
||||
|
||||
### YAGNI
|
||||
```ts
|
||||
// ❌ Speculative
|
||||
class User {
|
||||
constructor(public id, public email, public preferences = new Preferences()) {}
|
||||
// 매 preferences 의 미래 use 의 expect — 매 currently unused.
|
||||
}
|
||||
|
||||
// ✅ Add when needed
|
||||
class User {
|
||||
constructor(public id, public email) {}
|
||||
}
|
||||
// 매 future 의 add when needed.
|
||||
```
|
||||
|
||||
### Comment (when truly needed)
|
||||
```ts
|
||||
// ❌ Redundant
|
||||
// 매 increments i
|
||||
i++;
|
||||
|
||||
// ❌ Outdated
|
||||
// 매 returns user list (actually returns IDs now)
|
||||
function getUsers() { return ids; }
|
||||
|
||||
// ✅ Reason / non-obvious
|
||||
// 매 Use legacy auth path due to bug #1234 (waiting for upstream fix).
|
||||
// 매 Delete after 2026-12 (when fix lands).
|
||||
```
|
||||
|
||||
### ESLint config (clean code)
|
||||
```json
|
||||
{
|
||||
"rules": {
|
||||
"complexity": ["error", 10],
|
||||
"max-lines-per-function": ["warn", 50],
|
||||
"max-params": ["warn", 4],
|
||||
"max-depth": ["warn", 4],
|
||||
"no-magic-numbers": ["warn", { "ignore": [0, 1, -1] }],
|
||||
"id-length": ["warn", { "min": 2, "exceptions": ["i", "j", "_"] }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Boy Scout Rule (programmatic)
|
||||
```python
|
||||
# 매 PR 의 review 시 의 leave-better-than-found
|
||||
def pr_smell_check(diff):
|
||||
smells_in_changed = detect_smells(diff)
|
||||
if smells_in_changed > 0:
|
||||
suggest('Touched code has smells. Consider small cleanup in this PR.')
|
||||
```
|
||||
|
||||
## 🤔 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| New feature | KISS + YAGNI |
|
||||
| Long function | Extract Method |
|
||||
| Many params | Parameter Object |
|
||||
| Inheritance trap | Composition |
|
||||
| Cross-cutting | Strategy / decorator |
|
||||
| Magic number | Named constant |
|
||||
| Duplicate (3rd time) | Extract |
|
||||
| Unclear name | Rename refactor |
|
||||
|
||||
**기본값**: 매 SOLID 의 intent 의 understand + 매 boy scout. 매 dogma X.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Software-Engineering]] · [[Refactoring]] · [[Software-Craftsmanship]]
|
||||
- 변형: [[SOLID]] · [[DRY]] · [[KISS]] · [[YAGNI]] · [[POLA]]
|
||||
- 응용: [[Code_Smells]] · [[Refactoring]] · [[Clean-Architecture]]
|
||||
- 비판: [[Casey-Muratori-Critique]] · [[Anaemic-Domain-Model]]
|
||||
- Adjacent: [[Architecture-Anti-Patterns]] · [[Quality_Code_Review_Modern]] · [[Architecture-Styles]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 review. 매 refactor. 매 onboarding. 매 AI-generated code 의 quality check.
|
||||
**언제 X**: 매 prototype (premature). 매 simple script.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Dogma**: 매 모든 code 의 mechanical 적용.
|
||||
- **Over-abstraction**: 매 SOLID 의 imitate 의 bad design.
|
||||
- **Premature DRY**: 매 wrong abstraction.
|
||||
- **Over-decomposition**: 매 small function 의 maze.
|
||||
- **Comment 의 over-add**: 매 LLM 의 typical.
|
||||
- **No measurement**: 매 better 의 prove X.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Robert Martin "Clean Code", Fowler "Refactoring", Beck "Implementation Patterns").
|
||||
- 신뢰도 A (with caveats — 매 not gospel).
|
||||
- Related: [[Code_Smells]] · [[SOLID]] · [[Architecture-Styles]] · [[Refactoring]].
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — naming + SOLID + critique + 매 ESLint code |
|
||||
|
||||
Reference in New Issue
Block a user