Skills · Content & docs

Clean Code Framework

Unverified24/40

Write readable, maintainable code through disciplined naming, small functions, and clean error handling. Use when the user mentions "clean up this code", "this function is too long", "code smells", "naming conventions", "boy scout rule", "single responsibility

Originally by wondelai · MIT

Claude CodePartialHas SKILL.md but declares no allowed-tools — Claude Code will ask for permission each time
CursorPartialPlain prose you can paste in — but no Cursor rules file
CodexPartialPlain prose you can paste in — but no AGENTS.md
Gemini CLIPartialPlain prose you can paste in
CopilotPartialPlain prose you can paste in — but no Copilot instructions file
npx agentalley add clean-code

This command does not work yet — the CLI is still being built. Until then, use Raw in the reader below to take the file.

Who is stuck, and on what

Write readable, maintainable code through disciplined naming, small functions, and clean error handling. Use when the user mentions "clean up this code", "this function is too long", "code smells", "naming conventions", "boy scout rule", "single responsibility

The whole source

No sign-in, no blur, nothing truncated
clean-code/SKILL.md223 lines14.6 KBRawView on GitHub
Frontmatter — 4 properties
nameclean-code
descriptionWrite readable, maintainable code through disciplined naming, small functions, and clean error handling. Use when the user mentions "clean up this code", "this function is too long", "code smells", "naming conventions", "boy scout rule", "single responsibility", or "unit test quality". Also trigger when reviewing a pull request for readability, untangling a messy function, debating comment styles, or improving error-handling patterns. Covers SRP, comment discipline, formatting, and unit testing. For refactoring techniques, see refactoring-patterns. For architecture and dependency rules, see clean-architecture.
licenseMIT
metadata author: wondelai version: "1.4.0
1---
2name: clean-code
3description: 'Write readable, maintainable code through disciplined naming, small functions, and clean error handling. Use when the user mentions "clean up this code", "this function is too long", "code smells", "naming conventions", "boy scout rule", "single responsibility", or "unit test quality". Also trigger when reviewing a pull request for readability, untangling a messy function, debating comment styles, or improving error-handling patterns. Covers SRP, comment discipline, formatting, and unit testing. For refactoring techniques, see refactoring-patterns. For architecture and dependency rules, see clean-architecture.'B1Line is 632 characters — unreadable by eye
4license: MIT
5metadata:
6 author: wondelai
7 version: "1.4.0"
8---A5No allowed-tools declared — no way to tell what this skill may touch
9 
10# Clean Code Framework
11 
12A disciplined approach to writing code that communicates intent, minimizes surprises, and welcomes change. Apply these principles when writing new code, reviewing pull requests, refactoring legacy systems, or advising on code quality.
13 
14## Core Principle
15 
16**Code is read far more often than it is written — optimize for the reader.** The read-to-write ratio is well over 10:1, so every naming choice, function boundary, and formatting decision either adds clarity or adds cost. Clean code reads like well-written prose: names reveal intent, functions tell a story one step at a time, and the Boy Scout Rule applies — always leave the code cleaner than you found it.
17 
18## Scoring
19 
20**Goal: 10/10.** Rate any code 0-10 against the principles below. Report the current score and the specific improvements needed to reach 10/10.
21 
22- **9-10:** Names reveal intent, functions are small and focused, error handling is consistent, tests are clean and comprehensive
23- **7-8:** Mostly clean with minor naming ambiguities or a few long functions; tests may lack edge cases
24- **5-6:** Mixed — good patterns alongside unclear names, duplicated logic, or inconsistent error handling
25- **3-4:** Long multi-purpose functions, misleading names, poor or missing tests
26- **1-2:** Nearly unreadable — magic numbers, cryptic abbreviations, no structure, no tests
27 
28## The Clean Code Framework
29 
30Six disciplines for writing code that communicates clearly and adapts to change:
31 
32### 1. Meaningful Names
33 
34**Core concept:** Names should reveal intent, avoid disinformation, and make the code read like prose. If a name requires a comment to explain it, the name is wrong.
35 
36**Why it works:** Names are the most pervasive form of documentation — a well-chosen name eliminates the need to read the implementation; a poor one forces every reader to reverse-engineer intent.
37 
38**Key insights:**
39- A name should answer why it exists, what it does, and how it is used
40- No encodings, prefixes, or type information (no Hungarian notation); single letters only for tiny-scope loop counters
41- Classes are nouns; methods are verbs
42- One word per concept: don't mix `fetch`, `retrieve`, and `get`A4This skill pulls in web or user content but never says to treat that content as data. A signal, not proof.
43- Longer scope demands a longer, more descriptive name
44- Rename freely — IDEs make it trivial
45 
46**Code applications:**
47 
48| Context | Pattern | Example |
49|---------|---------|---------|
50| **Variables** | Intention-revealing | `elapsedTimeInDays` not `d` |
51| **Booleans** | Predicate phrasing | `isActive`, `hasPermission`, `canEdit` |
52| **Functions** | Verb + noun | `calculateMonthlyRevenue()` not `calc()` |
53| **Classes** | Noun naming the responsibility | `InvoiceGenerator` not `InvoiceManager` |
54 
55See [references/naming-conventions.md](references/naming-conventions.md) when renaming or reviewing names — per-language conventions, pronounceable/searchable tables, and before/after examples.
56 
57### 2. Functions
58 
59**Core concept:** Functions should be small, do one thing, and do it well — ideally 4-6 lines, zero to two arguments, one level of abstraction.
60 
61**Why it works:** Small single-purpose functions are easy to name, understand, test, and reuse; long functions hide bugs, resist testing, and accumulate responsibilities.
62 
63**Key insights:**
64- Step-Down Rule: code reads top-down, each function calling the next level of abstraction
65- Argument count: zero best, one fine, two acceptable, three+ requires justification
66- Flag arguments are a smell — the function does two things; split it
67- Command-Query Separation: change state or return a value, never both
68- Extract till you drop: if you can pull out a named function, do it
69- No hidden side effects — the name must tell the whole truth
70 
71**Code applications:**
72 
73| Context | Pattern | Example |
74|---------|---------|---------|
75| **Long function** | Extract named steps | `validateInput(); transformData(); saveRecord();` |
76| **Flag argument** | Split into two functions | `renderForPrint()` / `renderForScreen()` not `render(isPrint)` |
77| **Error cases** | Guard clauses at top | Early return for errors, single happy path |
78| **Many arguments** | Introduce parameter object | `new DateRange(start, end)` not `report(start, end, format, locale)` |
79| **Side effects** | Make effects explicit | `checkPassword()` that starts a session → rename or separate |
80 
81See [references/functions-and-methods.md](references/functions-and-methods.md) when splitting a long function — argument-count rules, command-query separation, and step-down worked examples.
82 
83### 3. Comments and Formatting
84 
85**Core concept:** A comment is a failure to express yourself in code. When comments are necessary, they explain *why*, never *what*. Formatting creates the visual structure that makes code scannable.
86 
87**Why it works:** Comments rot — code changes but comments often don't, creating documentation worse than none. Clean formatting lets developers scan code like a newspaper: headlines first, details on demand.
88 
89**Key insights:**
90- The best comment is a well-named extracted function
91- Acceptable: legal headers, TODOs, public API docs, genuine "why" explanations
92- Commented-out code and journal comments: delete — version control remembers
93- Vertical openness between concepts; vertical density within them; declare variables near usage
94- Newspaper metaphor: high-level functions at the top of the file, details below
95 
96**Code applications:**
97 
98| Context | Pattern | Example |
99|---------|---------|---------|
100| **Explaining "what"** | Replace with better name | `// check if eligible` → `isEligible()` |
101| **Explaining "why"** | Keep as comment | `// RFC 7231 requires this header for proxies` |
102| **Commented-out code** | Delete it | Trust version control |
103| **Team formatting** | Decide once, automate | Prettier, Black, gofmt |
104 
105See [references/comments-formatting.md](references/comments-formatting.md) when deciding whether a comment earns its place — good-vs-bad comment catalog and vertical-formatting rules.
106 
107### 4. Error Handling
108 
109**Core concept:** Error handling is a separate concern from business logic. Use exceptions rather than return codes, provide context with every exception, and never return or pass null.
110 
111**Why it works:** Return codes clutter the happy path with checks; exceptions separate the two cleanly. Returning null forces null checks on every caller, and one missing check crashes far from the source.
112 
113**Key insights:**
114- Write the try-catch first — it defines a transaction boundary
115- Prefer unchecked exceptions — checked ones violate the Open/Closed Principle
116- Define exception classes by the caller's needs, not the failure type
117- Don't return null (use empty collections, Optional, or throw); don't pass null either
118- Special Case / Null Object pattern: return an object with default behavior instead of null
119 
120**Code applications:**
121 
122| Context | Pattern | Example |
123|---------|---------|---------|
124| **Null returns** | Empty collection or Optional | `return Collections.emptyList()` not `return null` |
125| **Error codes** | Replace with exceptions | `throw new InsufficientFundsException(balance, amount)` |
126| **Third-party APIs** | Wrap with adapter | `PortfolioService` wraps the vendor API, translates its exceptions |
127| **Special cases** | Null Object pattern | `GuestUser` with default behavior instead of null checks |
128| **Context in errors** | Include operation + state | `"Failed to save invoice #1234 for customer 'Acme'"` |
129 
130See [references/error-handling.md](references/error-handling.md) when designing exception or null strategy — Special Case pattern and third-party-API wrapping examples.
131 
132### 5. Unit Testing
133 
134**Core concept:** Tests are first-class code, kept clean with the same discipline as production code. Dirty tests are worse than no tests — they become a liability that slows every change.
135 
136**Why it works:** Clean tests are executable documentation and a safety net for refactoring; dirty tests make every modification a fight through incomprehensible test code.
137 
138**Key insights:**
139- Three Laws of TDD: write a failing test first; only enough test to fail; only enough code to pass
140- One concept per test — one logical assertion, not necessarily one assert
141- F.I.R.S.T.: Fast, Independent, Repeatable, Self-validating, Timely
142- Build a domain-specific testing language: helpers that read like a DSL
143- Refactor test code as readily as production code
144 
145**Code applications:**
146 
147| Context | Pattern | Example |
148|---------|---------|---------|
149| **Test structure** | Arrange-Act-Assert | Setup, execute, verify — clearly separated |
150| **Test naming** | Scenario + expected behavior | `shouldRejectExpiredToken` not `test1` |
151| **Shared setup** | Builder/factory helpers | `aUser().withRole(ADMIN).build()` |
152| **Flaky tests** | Remove external dependencies | Mock time, network, file system |
153 
154See [references/testing-principles.md](references/testing-principles.md) when writing or cleaning tests — TDD laws, F.I.R.S.T. expanded, and clean-test patterns.
155 
156### 6. Code Smells and Heuristics
157 
158**Core concept:** Smells are surface indicators of deeper design problems — learn to recognize them quickly and apply targeted refactorings instead of vague "cleanup".
159 
160**Why it works:** Smells are heuristics that point toward likely problems without deep analysis, turning code review instinct into specific, repeatable moves.
161 
162**Key insights:**
163- Function smells: too many arguments, output arguments, flag arguments, dead functions
164- General smells: duplication, wrong level of abstraction, feature envy, magic numbers
165- Test smells: insufficient coverage, skipped tests, untested boundary conditions and failure paths
166- Refactor in small, tested steps — never refactor and add features simultaneously
167- Boy Scout Rule: leave the code cleaner than you found it
168 
169**Code applications:**
170 
171| Context | Pattern | Example |
172|---------|---------|---------|
173| **Duplication** | Extract shared logic | Common validation → `validateEmail()` helper |
174| **Feature envy** | Move method to the data's class | `order.calculateTotal()` not `calculator.total(order)` |
175| **Dead code** | Delete it | Remove unused functions, unreachable branches |
176| **Magic numbers** | Named constants | `MAX_LOGIN_ATTEMPTS = 5` not bare `5` |
177| **Shotgun surgery** | Consolidate related changes | Group scattered logic into a single module |
178 
179See [references/code-smells.md](references/code-smells.md) when a smell is hard to name — the full catalog by category, each paired with its targeted refactoring.
180 
181## Common Mistakes
182 
183| Mistake | Why It Fails | Fix |
184|---------|-------------|------|
185| **Abbreviating names** | Saves seconds writing, costs hours reading | Full descriptive names; IDEs autocomplete |
186| **"Clever" one-liners** | Impressive to write, impossible to debug | Expand into readable named steps |
187| **Comments instead of refactoring** | Comments rot; code is the truth | Extract a well-named function instead |
188| **Catching generic exceptions** | Swallows bugs along with expected errors | Catch specific exceptions; let the rest propagate |
189| **No tests for error paths** | Happy path works, edge cases crash | Test every branch, boundary, and failure mode |
190| **Premature optimization** | Obscures intent for marginal gains | Clean first; optimize measured bottlenecks |
191| **God classes** | One 2000-line class does everything | Apply SRP — split by responsibility |
192| **Refactoring without tests** | No safety net for regressions | Write characterization tests first |
193| **Inconsistent conventions** | Every file feels like a different codebase | Agree on style; enforce with linters and formatters |
194| **Returning null everywhere** | Null checks spread like a virus | Optional, empty collections, or Null Object |
195 
196## Quick Diagnostic
197 
198| Question | If No | Action |
199|----------|-------|--------|
200| Can you understand each function without reading its body? | Names don't reveal intent | Rename to describe what it does |
201| Are all functions under 20 lines? | Functions do too many things | Extract sub-operations into named helpers |
202| Zero commented-out code blocks? | Dead code creating confusion | Delete — version control has history |
203| Is error handling separate from business logic? | Try-catch clutters the main flow | Extract handlers; exceptions over return codes |
204| Does every class have a single responsibility? | Classes accumulate unrelated duties | Split into focused, well-named classes |
205| Is there a test for every public method? | No safety net for changes | Add tests before changing further |
206| Are test names descriptive of behavior? | Failures are hard to interpret | Rename to `shouldDoXWhenY` |
207| Is duplication below 3 occurrences? | Copy-paste spreading bugs | Extract shared logic (§6) |
208| Are magic numbers named constants? | Intent hidden behind raw values | Name the constant (§6) |
209| Do all tests run in under 10 seconds? | Slow tests don't get run | Mock external deps; split integration tests |
210 
211## Further Reading
212 
213Based on Robert C. Martin's seminal guide to software craftsmanship:
214 
215- [*"Clean Code: A Handbook of Agile Software Craftsmanship"*](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882?tag=wondelai00-20) by Robert C. Martin
216- [*"The Clean Coder: A Code of Conduct for Professional Programmers"*](https://www.amazon.com/Clean-Coder-Conduct-Professional-Programmers/dp/0137081073?tag=wondelai00-20) by Robert C. Martin
217- [*"Clean Architecture: A Craftsman's Guide to Software Structure and Design"*](https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164?tag=wondelai00-20) by Robert C. Martin
218- [*"Refactoring: Improving the Design of Existing Code"*](https://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Signature/dp/0134757599?tag=wondelai00-20) by Martin Fowler
219 
220## About the Author
221 
222**Robert C. Martin ("Uncle Bob")** has been programming since 1970, co-authored the Agile Manifesto, and founded Uncle Bob Consulting and Clean Coders. His books — *Clean Code*, *The Clean Coder*, *Clean Architecture*, and *Clean Agile* — shaped how a generation of developers think about code quality, and his core stance is that the only way to go fast is to go well.
223 

Reviews

Installed this one?Write the first review and take the Trailblazer badge.

Reviews only open after a real install, so this is empty — and we leave it empty rather than invent one.

Alternatives

Also in Content & docs