Clean Code
Be concise, direct, and solution-focused. Clean code reads like well-written prose — every name reveals intent, every function does one thing, and every abstraction earns its place.
Installation
OpenClaw / Moltbot / Clawbot
npx clawhub@latest install clean-code
Core Principles
| Principle |
Rule |
Practical Test |
| SRP |
Single Responsibility — each function/class does ONE thing |
"Can I describe what this does without using 'and'?" |
| DRY |
Don't Repeat Yourself — extract duplicates, reuse |
"Have I written this logic before?" |
| KISS |
Keep It Simple — simplest solution that works |
"Is there a simpler way to achieve this?" |
| YAGNI |
You Aren't Gonna Need It — don't build unused features |
"Does anyone need this right now?" |
| Boy Scout |
Leave code cleaner than you found it |
"Is this file better after my change?" |
Naming Rules
Names are the most important documentation. A good name eliminates the need for a comment.
| Element |
Convention |
Bad |
Good |
| Variables |
Reveal intent |
n, d, tmp |
userCount, elapsed, activeUsers |
| Functions |
Verb + noun |
user(), calc() |
getUserById(), calculateTotal() |
| Booleans |
Question form |
active, flag |
isActive, hasPermission, canEdit |
| Constants |
SCREAMING_SNAKE |
max, timeout |
MAX_RETRY_COUNT, REQUEST_TIMEOUT_MS |
| Classes |
Noun, singular |
Manager, Data |
UserRepository, OrderService |
| Enums |
PascalCase values |
'pending' string |
Status.Pending |
Rule: If you need a comment to explain a name, rename it.
Naming Anti-Patterns
| Anti-Pattern |
Problem |
Fix |
Cryptic abbreviations (usrMgr, cfg) |
Unreadable in 6 months |
Spell it out — IDE autocomplete makes long names free |
Generic names (data, info, item, handler) |
Says nothing about purpose |
Use domain-specific names that reveal intent |
Misleading names (getUserList returns one user) |
Actively deceives readers |
Match name to behavior, or change the behavior |
Hungarian notation (strName, nCount, IUser) |
Redundant with type system |
Let TypeScript/IDE show types; names describe purpose |
Function Rules
| Rule |
Guideline |
Why |
| Small |
Max 20 lines, ideally 5-10 |
Fits in your head |
| One Thing |
Does one thing, does it well |
Testable and nameable |
| One Level |
One level of abstraction per function |
Readable top to bottom |
| Few Args |
Max 3 arguments, prefer 0-2 |
Easy to call correctly |
| No Side Effects |
Don't mutate inputs unexpectedly |
Predictable behavior |
Guard Clauses
Flatten nested conditionals with early returns. Never nest deeper than 2 levels.
// BAD — 5 levels deep
function processOrder(order: Order) {
if (order) {
if (order.items.length > 0) {
if (order.customer) {
if (order.customer.isVerified) {
return submitOrder(order);
}
}
}
}
throw new Error('Invalid order');
}
// GOOD — guard clauses flatten the structure
function processOrder(order: Order) {
if (!order) throw new Error('No order');
if (!order.items.length) throw new Error('No items');
if (!order.customer) throw new Error('No customer');
if (!order.customer.isVerified) throw new Error('Customer not verified');
return submitOrder(order);
}
Parameter Objects
When a function needs more than 3 arguments, use an options object.
// BAD — too many parameters, order matters
createUser('John', 'Doe', 'john@example.com', 'secret', 'admin', 'Engineering');
// GOOD — self-documenting options object
createUser({
firstName: 'John',
lastName: 'Doe',
email: 'john@example.com',
password: 'secret',
role: 'admin',
department: 'Engineering',
});
Code Structure Patterns
| Pattern |
When to Apply |
Benefit |
| Guard Clauses |
Edge cases at function start |
Flat, readable flow |
| Flat > Nested |
Any nesting beyond 2 levels |
Reduced cognitive load |
| Composition |
Complex operations |
Small, testable pieces |
| Colocation |
Related code across files |
Easier to find and change |
| Extract Function |
Comments separating "sections" |
Self-documenting code |
Composition Over God Functions
// BAD — god function doing everything
async function processOrder(order: Order) {
// Validate... (15 lines)
// Calculate totals... (15 lines)
// Process payment... (10 lines)
// Send notifications... (10 lines)
// Update inventory... (10 lines)
return { success: true };
}
// GOOD — composed of small, focused functions
async function processOrder(order: Order) {
validateOrder(order);
const totals = calculateOrderTotals(order);
const payment = await processPayment(order.customer, totals);
await sendOrderConfirmation(order, payment);
await updateInventory(order.items);
return { success: true, orderId: payment.orderId };
}
Return Type Consistency
Functions should return consistent types. Use discriminated unions for multiple outcomes.
// BAD — returns different types
function getUser(id: string) {
const user = database.find(id);
if (!user) return false; // boolean
if (user.isDeleted) return null; // null
return user; // User
}
// GOOD — discriminated union
type GetUserResult =
| { status: 'found'; user: User }
| { status: 'not_found' }
| { status: 'deleted' };
function getUser(id: string): GetUserResult {
const user = database.find(id);
if (!user) return { status: 'not_found' };
if (user.isDeleted) return { status: 'deleted' };
return { status: 'found', user };
}
Anti-Patterns
| Anti-Pattern |
Problem |
Fix |
| Comment every line |
Noise obscures signal |
Delete obvious comments; comment why, not what |
| Helper for one-liner |
Unnecessary indirection |
Inline the code |
| Factory for 2 objects |
Over-engineering |
Direct instantiation |
utils.ts with 1 function |
Junk drawer file |
Put code where it's used |
| Deep nesting |
Unreadable flow |
Guard clauses and early returns |
| Magic numbers |
Unclear intent |
Named constants |
| God functions |
Untestable, unreadable |
Split by responsibility |
| Commented-out code |
Dead code confusion |
Delete it; git remembers |
| TODO sprawl |
Never gets done |
Track in issue tracker, not code |
| Premature abstraction |
Wrong abstraction is worse than none |
Wait for 3+ duplicates before abstracting |
| Copy-paste programming |
Duplicated bugs |
Extract shared logic |
| Exception-driven control flow |
Slow and confusing |
Use explicit conditionals |
| Stringly-typed code |
Typos and missed cases |
Use enums or union types |
| Callback hell |
Pyramid of doom |
Use async/await |
Pre-Edit Safety Check
Before changing any file, answer these questions to avoid cascading breakage:
| Question |
Why |
| What imports this file? |
Dependents might break on interface changes |
| What does this file import? |
You might need to update the contract |
| What tests cover this? |
Tests might fail — update them alongside code |
| Is this a shared component? |
Multiple consumers means wider blast radius |
File to edit: UserService.ts
├── Who imports this? → UserController.ts, AuthController.ts
├── Do they need changes too? → Check function signatures
└── What tests cover this? → UserService.test.ts
Rule: Edit the file + all dependent files in the SAME task. Never leave broken imports or missing updates.
Self-Check Before Completing
Before marking any task complete, verify:
| Check |
Question |
| Goal met? |
Did I do exactly what was asked? |
| Files edited? |
Did I modify all necessary files, including dependents? |
| Code works? |
Did I verify the change compiles and runs? |
| No errors? |
Do lint and type checks pass? |
| Nothing forgotten? |
Any edge cases or dependent files missed? |
NEVER Do
- NEVER add comments that restate the code — if the code needs a comment to explain what it does, rename things until it doesn't
- NEVER create abstractions for fewer than 3 use cases — premature abstraction is worse than duplication
- NEVER leave commented-out code in the codebase — delete it; version control exists for history
- NEVER write functions longer than 20 lines — extract sub-functions until each does one thing
- NEVER nest deeper than 2 levels — use guard clauses, early returns, or extract functions
- NEVER use magic numbers or strings — define named constants with clear semantics
- NEVER edit a file without checking what depends on it — broken imports and missing updates are the most common source of bugs in multi-file changes
- NEVER leave a task with failing lint or type checks — fix all errors before marking complete
References
Detailed guides for specific clean code topics:
| Reference |
Description |
| Anti-Patterns |
21 common mistakes with bad/good code examples across naming, functions, structure, and comments |
| Code Smells |
Classic code smells catalog with detection patterns — Bloaters, OO Abusers, Change Preventers, Dispensables, Couplers |
| Refactoring Catalog |
Essential refactoring patterns with before/after examples and step-by-step mechanics |
1---
2name: clean-code
3model: standard
4category: testing
5description: Pragmatic coding standards for writing clean, maintainable code — naming, functions, structure, anti-patterns, and pre-edit safety checks. Use when writing new code, refactoring existing code, reviewing code quality, or establishing coding standards.
6version: 2.0
7metadata:
8 source: https://skillmd.com/skills/modbender/clean-code
9---
10
11# Clean Code
12
13> Be **concise, direct, and solution-focused**. Clean code reads like well-written prose — every name reveals intent, every function does one thing, and every abstraction earns its place.
14
15
16## Installation
17
18### OpenClaw / Moltbot / Clawbot
19
20```bash
21npx clawhub@latest install clean-code
22```
23
24
25---
26
27## Core Principles
28
29| Principle | Rule | Practical Test |
30|-----------|------|----------------|
31| **SRP** | Single Responsibility — each function/class does ONE thing | "Can I describe what this does without using 'and'?" |
32| **DRY** | Don't Repeat Yourself — extract duplicates, reuse | "Have I written this logic before?" |
33| **KISS** | Keep It Simple — simplest solution that works | "Is there a simpler way to achieve this?" |
34| **YAGNI** | You Aren't Gonna Need It — don't build unused features | "Does anyone need this right now?" |
35| **Boy Scout** | Leave code cleaner than you found it | "Is this file better after my change?" |
36
37---
38
39## Naming Rules
40
41Names are the most important documentation. A good name eliminates the need for a comment.
42
43| Element | Convention | Bad | Good |
44|---------|------------|-----|------|
45| **Variables** | Reveal intent | `n`, `d`, `tmp` | `userCount`, `elapsed`, `activeUsers` |
46| **Functions** | Verb + noun | `user()`, `calc()` | `getUserById()`, `calculateTotal()` |
47| **Booleans** | Question form | `active`, `flag` | `isActive`, `hasPermission`, `canEdit` |
48| **Constants** | SCREAMING_SNAKE | `max`, `timeout` | `MAX_RETRY_COUNT`, `REQUEST_TIMEOUT_MS` |
49| **Classes** | Noun, singular | `Manager`, `Data` | `UserRepository`, `OrderService` |
50| **Enums** | PascalCase values | `'pending'` string | `Status.Pending` |
51
52> **Rule:** If you need a comment to explain a name, rename it.
53
54### Naming Anti-Patterns
55
56| Anti-Pattern | Problem | Fix |
57|--------------|---------|-----|
58| Cryptic abbreviations (`usrMgr`, `cfg`) | Unreadable in 6 months | Spell it out — IDE autocomplete makes long names free |
59| Generic names (`data`, `info`, `item`, `handler`) | Says nothing about purpose | Use domain-specific names that reveal intent |
60| Misleading names (`getUserList` returns one user) | Actively deceives readers | Match name to behavior, or change the behavior |
61| Hungarian notation (`strName`, `nCount`, `IUser`) | Redundant with type system | Let TypeScript/IDE show types; names describe purpose |
62
63---
64
65## Function Rules
66
67| Rule | Guideline | Why |
68|------|-----------|-----|
69| **Small** | Max 20 lines, ideally 5-10 | Fits in your head |
70| **One Thing** | Does one thing, does it well | Testable and nameable |
71| **One Level** | One level of abstraction per function | Readable top to bottom |
72| **Few Args** | Max 3 arguments, prefer 0-2 | Easy to call correctly |
73| **No Side Effects** | Don't mutate inputs unexpectedly | Predictable behavior |
74
75### Guard Clauses
76
77Flatten nested conditionals with early returns. Never nest deeper than 2 levels.
78
79```typescript
80// BAD — 5 levels deep
81function processOrder(order: Order) {
82 if (order) {
83 if (order.items.length > 0) {
84 if (order.customer) {
85 if (order.customer.isVerified) {
86 return submitOrder(order);
87 }
88 }
89 }
90 }
91 throw new Error('Invalid order');
92}
93
94// GOOD — guard clauses flatten the structure
95function processOrder(order: Order) {
96 if (!order) throw new Error('No order');
97 if (!order.items.length) throw new Error('No items');
98 if (!order.customer) throw new Error('No customer');
99 if (!order.customer.isVerified) throw new Error('Customer not verified');
100
101 return submitOrder(order);
102}
103```
104
105### Parameter Objects
106
107When a function needs more than 3 arguments, use an options object.
108
109```typescript
110// BAD — too many parameters, order matters
111createUser('John', 'Doe', 'john@example.com', 'secret', 'admin', 'Engineering');
112
113// GOOD — self-documenting options object
114createUser({
115 firstName: 'John',
116 lastName: 'Doe',
117 email: 'john@example.com',
118 password: 'secret',
119 role: 'admin',
120 department: 'Engineering',
121});
122```
123
124---
125
126## Code Structure Patterns
127
128| Pattern | When to Apply | Benefit |
129|---------|--------------|---------|
130| **Guard Clauses** | Edge cases at function start | Flat, readable flow |
131| **Flat > Nested** | Any nesting beyond 2 levels | Reduced cognitive load |
132| **Composition** | Complex operations | Small, testable pieces |
133| **Colocation** | Related code across files | Easier to find and change |
134| **Extract Function** | Comments separating "sections" | Self-documenting code |
135
136### Composition Over God Functions
137
138```typescript
139// BAD — god function doing everything
140async function processOrder(order: Order) {
141 // Validate... (15 lines)
142 // Calculate totals... (15 lines)
143 // Process payment... (10 lines)
144 // Send notifications... (10 lines)
145 // Update inventory... (10 lines)
146 return { success: true };
147}
148
149// GOOD — composed of small, focused functions
150async function processOrder(order: Order) {
151 validateOrder(order);
152 const totals = calculateOrderTotals(order);
153 const payment = await processPayment(order.customer, totals);
154 await sendOrderConfirmation(order, payment);
155 await updateInventory(order.items);
156 return { success: true, orderId: payment.orderId };
157}
158```
159
160---
161
162## Return Type Consistency
163
164Functions should return consistent types. Use discriminated unions for multiple outcomes.
165
166```typescript
167// BAD — returns different types
168function getUser(id: string) {
169 const user = database.find(id);
170 if (!user) return false; // boolean
171 if (user.isDeleted) return null; // null
172 return user; // User
173}
174
175// GOOD — discriminated union
176type GetUserResult =
177 | { status: 'found'; user: User }
178 | { status: 'not_found' }
179 | { status: 'deleted' };
180
181function getUser(id: string): GetUserResult {
182 const user = database.find(id);
183 if (!user) return { status: 'not_found' };
184 if (user.isDeleted) return { status: 'deleted' };
185 return { status: 'found', user };
186}
187```
188
189---
190
191## Anti-Patterns
192
193| Anti-Pattern | Problem | Fix |
194|--------------|---------|-----|
195| Comment every line | Noise obscures signal | Delete obvious comments; comment *why*, not *what* |
196| Helper for one-liner | Unnecessary indirection | Inline the code |
197| Factory for 2 objects | Over-engineering | Direct instantiation |
198| `utils.ts` with 1 function | Junk drawer file | Put code where it's used |
199| Deep nesting | Unreadable flow | Guard clauses and early returns |
200| Magic numbers | Unclear intent | Named constants |
201| God functions | Untestable, unreadable | Split by responsibility |
202| Commented-out code | Dead code confusion | Delete it; git remembers |
203| TODO sprawl | Never gets done | Track in issue tracker, not code |
204| Premature abstraction | Wrong abstraction is worse than none | Wait for 3+ duplicates before abstracting |
205| Copy-paste programming | Duplicated bugs | Extract shared logic |
206| Exception-driven control flow | Slow and confusing | Use explicit conditionals |
207| Stringly-typed code | Typos and missed cases | Use enums or union types |
208| Callback hell | Pyramid of doom | Use async/await |
209
210---
211
212## Pre-Edit Safety Check
213
214Before changing any file, answer these questions to avoid cascading breakage:
215
216| Question | Why |
217|----------|-----|
218| **What imports this file?** | Dependents might break on interface changes |
219| **What does this file import?** | You might need to update the contract |
220| **What tests cover this?** | Tests might fail — update them alongside code |
221| **Is this a shared component?** | Multiple consumers means wider blast radius |
222
223```
224File to edit: UserService.ts
225├── Who imports this? → UserController.ts, AuthController.ts
226├── Do they need changes too? → Check function signatures
227└── What tests cover this? → UserService.test.ts
228```
229
230> **Rule:** Edit the file + all dependent files in the SAME task. Never leave broken imports or missing updates.
231
232---
233
234## Self-Check Before Completing
235
236Before marking any task complete, verify:
237
238| Check | Question |
239|-------|----------|
240| **Goal met?** | Did I do exactly what was asked? |
241| **Files edited?** | Did I modify all necessary files, including dependents? |
242| **Code works?** | Did I verify the change compiles and runs? |
243| **No errors?** | Do lint and type checks pass? |
244| **Nothing forgotten?** | Any edge cases or dependent files missed? |
245
246---
247
248## NEVER Do
249
2501. **NEVER add comments that restate the code** — if the code needs a comment to explain *what* it does, rename things until it doesn't
2512. **NEVER create abstractions for fewer than 3 use cases** — premature abstraction is worse than duplication
2523. **NEVER leave commented-out code in the codebase** — delete it; version control exists for history
2534. **NEVER write functions longer than 20 lines** — extract sub-functions until each does one thing
2545. **NEVER nest deeper than 2 levels** — use guard clauses, early returns, or extract functions
2556. **NEVER use magic numbers or strings** — define named constants with clear semantics
2567. **NEVER edit a file without checking what depends on it** — broken imports and missing updates are the most common source of bugs in multi-file changes
2578. **NEVER leave a task with failing lint or type checks** — fix all errors before marking complete
258
259---
260
261## References
262
263Detailed guides for specific clean code topics:
264
265| Reference | Description |
266|-----------|-------------|
267| [Anti-Patterns](references/anti-patterns.md) | 21 common mistakes with bad/good code examples across naming, functions, structure, and comments |
268| [Code Smells](references/code-smells.md) | Classic code smells catalog with detection patterns — Bloaters, OO Abusers, Change Preventers, Dispensables, Couplers |
269| [Refactoring Catalog](references/refactoring-catalog.md) | Essential refactoring patterns with before/after examples and step-by-step mechanics |