d8a80f6272
이름만 다른(표기 변형) [[위키링크]]를 대상 문서의 canonical 제목으로 치환해 끊겼던 1,200개 링크를 연결. 제목/파일명 정규화 일치만 적용하고 별칭 매칭은 과병합 위험으로 제외(애매성 가드). 원본은 _link_reconcile_backup/ 에 백업. 도구: Datacollect/scripts/link_reconcile_apply.mjs Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
265 lines
7.5 KiB
Markdown
265 lines
7.5 KiB
Markdown
---
|
|
id: wiki-2026-0508-clean-code-principles
|
|
title: Clean Code Principles
|
|
category: 10_Wiki/Topics
|
|
status: verified
|
|
canonical_id: self
|
|
aliases: [clean code, SOLID, DRY, KISS, YAGNI, Robert Martin, Uncle Bob, naming, function rules]
|
|
duplicate_of: none
|
|
source_trust_level: A
|
|
confidence_score: 0.9
|
|
verification_status: applied
|
|
tags: [clean-code, solid, dry, kiss, refactoring, software-craftsmanship, naming, code-quality]
|
|
raw_sources: []
|
|
last_reinforced: 2026-05-10
|
|
github_commit: pending
|
|
tech_stack:
|
|
language: language-agnostic
|
|
framework: any
|
|
---
|
|
|
|
# Clean Code Principles
|
|
|
|
## 📌 한 줄 통찰
|
|
> **"매 code 의 communication 의 tool"**. 매 machine 보다 매 future-self / 매 colleague. Robert Martin (Uncle Bob) 의 catalog 가, 매 dogma 의 risk. 매 modern AI 시대 의 maintainability 의 even more critical.
|
|
|
|
## 매 핵심 principle
|
|
|
|
### Naming
|
|
- **Intention-revealing**: `daysSinceLastLogin` > `d`.
|
|
- **Searchable**: 매 unique enough.
|
|
- **Pronounceable**: 매 conversation 의 가능.
|
|
- **Avoid mental mapping**: `i` 의 single-letter 의 OK 만 매 small loop.
|
|
|
|
### 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).
|
|
|
|
### 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.
|
|
|
|
### 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**.
|
|
|
|
### 매 critique (Casey Muratori, others)
|
|
- 매 over-abstraction.
|
|
- 매 small function 의 maze.
|
|
- 매 SOLID 의 mechanical 적용 의 bad design.
|
|
- 매 dogma 의 trap.
|
|
|
|
→ 매 principle 의 intent 의 understand. 매 mechanical 적용 X.
|
|
|
|
### 매 modern context
|
|
- 매 AI-generated code 의 review 의 base.
|
|
- 매 LLM 의 sometimes good naming, 매 sometimes verbose.
|
|
- 매 comment 의 LLM 의 over-add 의 trim.
|
|
|
|
## 💻 패턴
|
|
|
|
### Naming (TS)
|
|
```ts
|
|
// ❌ Bad
|
|
const d = new Date();
|
|
const ut = users.filter(u => u.lt < d - 30);
|
|
|
|
// ✅ Good
|
|
const today = new Date();
|
|
const inactiveUsers = users.filter(u =>
|
|
u.lastLoginDate < addDays(today, -30)
|
|
);
|
|
```
|
|
|
|
### Function size
|
|
```ts
|
|
// ❌ Long function
|
|
function processOrder(order) {
|
|
// 매 50 line: validate, calculate tax, calculate shipping,
|
|
// apply discount, save to db, send email, log audit...
|
|
}
|
|
|
|
// ✅ Decomposed
|
|
function processOrder(order) {
|
|
validate(order);
|
|
const total = calculateTotal(order);
|
|
persist(order, total);
|
|
notify(order);
|
|
audit(order);
|
|
}
|
|
```
|
|
|
|
### SRP (Single Responsibility)
|
|
```ts
|
|
// ❌ Multiple responsibility
|
|
class User {
|
|
save() { db.save(this); }
|
|
sendEmail() { mailer.send(this.email, ...); }
|
|
hashPassword() { ... }
|
|
validateInput() { ... }
|
|
}
|
|
|
|
// ✅ 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) { ... } }
|
|
```
|
|
|
|
### 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
|
|
}
|
|
|
|
// ✅ 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
|
|
- 부모: [[Refactoring_Best_Practices|Refactoring]]
|
|
- 변형: [[SOLID]] · [[DRY]] · [[KISS]] · [[YAGNI]]
|
|
- 응용: [[Code_Smells]] · [[Refactoring_Best_Practices|Refactoring]] · [[Clean-Architecture]]
|
|
- 비판: [[Anaemic Domain Model]]
|
|
- Adjacent: [[Architecture Anti-patterns]] · [[Quality_Code_Review_Modern]] · [[Software 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]] · [[Software Architecture Styles]] · [[Refactoring_Best_Practices|Refactoring]].
|
|
|
|
## 🕓 Changelog
|
|
| 날짜 | 변경 |
|
|
|---|---|
|
|
| 2026-05-08 | Phase 1 |
|
|
| 2026-05-10 | Manual cleanup — naming + SOLID + critique + 매 ESLint code |
|