7.5 KiB
7.5 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-clean-code-principles | Clean Code Principles | 10_Wiki/Topics | verified | self |
|
none | A | 0.9 | applied |
|
2026-05-10 | pending |
|
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)
- S — Single Responsibility: 매 1 reason to change.
- O — Open/Closed: 매 extend 의 OK, 매 modify 의 X.
- L — Liskov Substitution: 매 subclass 의 swap 의 OK.
- I — Interface Segregation: 매 small + focused interface.
- 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)
// ❌ 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
// ❌ 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)
// ❌ 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)
// ❌ 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
// ❌ 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)
// ❌ 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
// ❌ 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)
// ❌ 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)
{
"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)
# 매 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 |