wpank

Clean Code

开发编程v1.0.0
作者:wpank更新于 2026-05-11clean-code-review@clawhub_wpank/clean-code-review
代码生成代码审查

据 AlphaMoat 统计,截至 2026-10,Clean Code 累计下载 12,763 次、获 8 个星标,按累计下载量在本次参与排名的 10,914 个 AI 技能中排名第 2,186 位,在「开发编程」分类(1,069 个)中排名第 159 位。

列表默认按累计下载量排序,也可按星标排序;详情页排名按累计下载量计算。

累计下载
1.3万
星标
8
全站下载量排名
#2,186
全站前 21% · 「开发编程」前 15%
平台累计下载星标评论
ClawHub ↗5,6586-
SkillHub ↗1.3万8—

各平台的计数口径不同,统计时间不一致。

这个技能是做什么的

覆盖命名、函数拆分、结构与常见反模式,并要求写码或重构前先做安全检查。硬规则包括:不写复述代码的注释、用例不足三个就不抽抽象、不留注释掉的死代码、嵌套不超过两层;改动要在同一任务里连同依赖文件一起改完,不留断掉的引用。 生成的建议仅作起点;按项目环境和可靠来源核实版本细节与事实,不要把示例当作实测结果。

资料发布于 2026-10-27

可以用来做什么

  • 重构一段嵌套过深的函数
  • 提交前按规则过一遍命名与死代码

什么时候用

  • 写新模块想先定规范时
  • 接手他人代码需要统一风格时

示例提示词

以下是根据技能文档生成的示例,不代表实际运行结果。

按这些规则重构这段函数并说明改动
检查这个文件有没有违反命名和嵌套限制

月度数据趋势

累计下载1.3万
3,6078,5241.3万2026-03 · 累计下载 4,2852026-05 · 累计下载 5,9292026-06 · 累计下载 6,7472026-07 · 累计下载 7,8532026-08 · 累计下载 8,7562026-09 · 累计下载 1.0万2026-10 · 累计下载 1.3万26-0326-0926-10
星标8
6782026-03 · 星标 62026-05 · 星标 82026-06 · 星标 82026-07 · 星标 82026-08 · 星标 82026-09 · 星标 82026-10 · 星标 826-0326-0926-10

2026-09 起统计方法调整:同名技能按作者分别统计,并覆盖全部技能。图中虚线为调整前的月份,与之后的数据不直接比较,也不计算跨越调整的增长。 该技能有同名的其他版本,调整前的数据归属当前下载量最大的这一个。

月份累计下载环比星标
2026-101.3万—8
2026-091.0万—8
2026-088,756+11.5%8
2026-077,853+16.4%8
2026-066,747+13.8%8
2026-055,929—8
2026-034,285—6

SKILL.md 原文

以下是作者发布的原始文件,按纯文本显示,本站未做修改或审核;其中的链接不可点击,命令请核实后再运行。抓取于 2026-10-23。

9.9 KB · ClawHub v1.0.0
---
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
---

# Clean Code
展开全部(共 268 行)
> 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

```bash
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.

```typescript
// 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.

```typescript
// 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',
});
```

---

## 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

```typescript
// 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.

```typescript
// 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

1. **NEVER add comments that restate the code** — if the code needs a comment to explain *what* it does, rename things until it doesn't
2. **NEVER create abstractions for fewer than 3 use cases** — premature abstraction is worse than duplication
3. **NEVER leave commented-out code in the codebase** — delete it; version control exists for history
4. **NEVER write functions longer than 20 lines** — extract sub-functions until each does one thing
5. **NEVER nest deeper than 2 levels** — use guard clauses, early returns, or extract functions
6. **NEVER use magic numbers or strings** — define named constants with clear semantics
7. **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
8. **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](references/anti-patterns.md) | 21 common mistakes with bad/good code examples across naming, functions, structure, and comments |
| [Code Smells](references/code-smells.md) | Classic code smells catalog with detection patterns — Bloaters, OO Abusers, Change Preventers, Dispensables, Couplers |
| [Refactoring Catalog](references/refactoring-catalog.md) | Essential refactoring patterns with before/after examples and step-by-step mechanics |

「开发编程」分类下的热门技能

编程大神.Skill开发编程

【全栈能力】编程大神.Skill:面向复杂真实项目的高阶全栈编程助手。不止生成代码,而是从一句目标接手陌生代码库,拆解需求、补齐实现、追到根因、完成重构、联调前后端,并把结果推进到能运行、能验证、能交付。覆盖 Web、后端、脚本、iOS、安卓、鸿蒙 ArkUI、微信小程序及其他技术栈,支持中英文工程、疑难 Bug、跨模块任务和长任务续做;用构建、日志、真实入口、设备或接口证据说明结果。仅问概念时直接回答,要求落地时持续推进到验收或明确阻塞。

↓ 1125.9万★ 82u_42bbb65f
编程专家Pro.Skill开发编程

编程专家 Pro:融合编程专家 2.0.3 工程专题与编程大神的鸿蒙 ArkTS/ArkUI、微信小程序和小游戏开发资料。用于项目实现、根因调试、审查、重构、测试、架构性能分析及多端开发验证。支持自然语言和 @专题标识,按任务读取包内知识;只问概念时直接回答。

↓ 626.9万★ 32user_47d655f0
编程专家.Skill开发编程

编程专家.Skill P8级编程助手,25年实战经验技能Skill,全栈:Java/Php网站/软件项目、API设计、Bug诊断、代码生成、代码审查、重构、测试用例、性能基准、技术选型、文档生成、任务拆解、Spec驱动、Karpathy规范、CMS二次开发、前端设计、MySQL/Mariadb、项目知识图谱,以及工程纪律层(根因调试硬闭环、阶段导航、事故复盘/SLO、威胁建模/供应链安全、生产就绪/渐进式发布、AI编码治理、面向Agent代码可读性、LLM应用安全)。支持 @标识 显式调用跳过路由。

↓ 600.7万★ 378user_741dc82b
dev-expert开发编程

编程专家.Skill P8级编程助手,25年实战经验技能Skill,全栈:Java/Php网站/软件项目、API设计、Bug诊断、代码生成、代码审查、重构、测试用例、性能基准、技术选型、文档生成、任务拆解、Spec驱动、Karpathy规范、CMS二次开发、前端设计、MySQL/Mariadb、项目知识图谱,以及工程纪律层(根因调试硬闭环、阶段导航、事故复盘/SLO、威胁建模/供应链安全、生产就绪/渐进式发布、AI编码治理、面向Agent代码可读性、LLM应用安全)。支持 @标识 显式调用跳过路由。

↓ 528.1万★ 32user_814dbe54
dev-expert-pro开发编程

编程专家 Pro:融合编程专家 2.0.3 工程专题与编程大神的鸿蒙 ArkTS/ArkUI、微信小程序和小游戏开发资料。用于项目实现、根因调试、审查、重构、测试、架构性能分析及多端开发验证。支持自然语言和 @专题标识,按任务读取包内知识;只问概念时直接回答。

↓ 104.7万★ -user_814dbe54
编程专家 Pro开发编程

编程专家 Pro:融合编程专家 2.0.3 工程专题与编程大神的鸿蒙 ArkTS/ArkUI、微信小程序和小游戏开发资料。用于项目实现、根因调试、审查、重构、测试、架构性能分析及多端开发验证。支持自然语言和 @专题标识,按任务读取包内知识;只问概念时直接回答。

↓ 98.2万★ 1user_28275a78
编程专家.Skill开发编程

编程专家.Skill P8级编程助手,25年实战经验技能Skill,全栈:Java/Php网站/软件项目、API设计、Bug诊断、代码生成、代码审查、重构、测试用例、性能基准、技术选型、文档生成、任务拆解、Spec驱动、Karpathy规范、CMS二次开发、前端设计、MySQL/Mariadb、项目知识图谱,以及工程纪律层(根因调试硬闭环、阶段导航、事故复盘/SLO、威胁建模/供应链安全、生产就绪/渐进式发布、AI编码治理、面向Agent代码可读性、LLM应用安全)。支持 @标识 显式调用跳过路由。

↓ 70.1万★ 6user_613b33ea
Github开发编程

用 gh 命令行工具查看 GitHub 上的 PR 检查、工作流运行与 API 查询的技能。

↓ 48.0万★ 714Peter Steinberger

wpank 的其他技能

数据月份:2026-10 · 下载/星标数聚合自公开技能注册库(ClawHub、SkillHub),按月更新。口径说明见数据方法。