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.
数据来源:ClawHub。 在 ClawSkills 查看
选择你使用的 Agent
方法一:命令行安装(推荐)
推荐(无需提前安装 clawhub)
npx clawhub@latest --dir ~/.claude/skills install clean-code-review或使用 clawhub CLI(需提前安装)
clawhub --dir ~/.claude/skills install clean-code-review⚠️ 需要 Node.js 18+,没有 Node?请使用下方方法二直接下载 ZIP。 安装 Node.js →
方法二:手动下载安装(无需 Node)
下载 ZIP,解压后将文件夹放到以下路径,重启 Agent 即可:
安装路径
~/.claude/skills/clean-code-review/💡解压后将文件夹放到上方路径,重启 Agent 即可生效
--- name: clean-code model: standard category: testing description: 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. version: 2.0 ---
> 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.
npx clawhub@latest install clean-code
---
| 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?" |
---
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.
| 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 |
---
| 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 |
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);
}
When a function needs more than 3 arguments, use an options object.
// BAD — too many parameters, order matters
createUser('John', 'Doe', '[email protected]', 'secret', 'admin', 'Engineering');
// GOOD — self-documenting options object
createUser({
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
password: 'secret',
role: 'admin',
department: 'Engineering',
});
---
| 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 |
// 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 };
}
---
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-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 |
---
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 |
...
安装 Clean Code 后,可以对 AI 说这些话来触发它
Help me get started with Clean Code
Explains what Clean Code does, walks through the setup, and runs a quick demo based on your current project
Use Clean Code to pragmatic coding standards for writing clean, maintainable code — n...
Invokes Clean Code with the right parameters and returns the result directly in the conversation
What can I do with Clean Code in my developer & devops workflow?
Lists the top use cases for Clean Code, with example commands for each scenario
将技能文件夹放到 ~/.claude/skills/clean-code-review/ 目录(个人级,所有项目可用),或 .claude/skills/clean-code-review/(项目级)。重启 AI 客户端后,用 /clean-code-review 主动调用,或让 AI 根据上下文自动发现并使用。
Clean Code 支持 Claude、Cursor、OpenClaw,可与这些 AI 平台无缝集成,扩展其能力。
Clean Code 可免费安装使用。请查阅仓库了解许可证信息。
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.
Clean Code 属于「Developer & DevOps」分类,该分类的技能帮助 AI 智能体在此领域执行专业任务。
Automate my developer & devops tasks using Clean Code
Identifies repetitive steps in your workflow and sets up Clean Code to handle them automatically