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 ↗56586-
SkillHub ↗1.3萬8—

各平台的計數口徑不同,統計時間不一致。

這個技能是做什麼的

覆蓋命名、函式拆分、結構與常見反模式,並要求寫碼或重構前先做安全檢查。硬規則包括:不寫複述程式碼的註釋、用例不足三個就不抽抽象、不留註釋掉的死程式碼、巢狀不超過兩層;改動要在同一任務裡連同依賴檔案一起改完,不留斷掉的引用。 生成的建議僅供起點參考;依專案環境和可靠來源核實版本細節與事實,不要把範例當作實測結果。

資料釋出於 2026-10-27

可以用來做什麼

  • 重構一段巢狀過深的函式
  • 提交前按規則過一遍命名與死程式碼

什麼時候用

  • 寫新模組想先定規範時
  • 接手他人程式碼需要統一風格時

示例提示詞

以下是根據技能文件生成的示例,不代表實際執行結果。

按這些規則重構這段函式並說明改動
檢查這個檔案有沒有違反命名和巢狀限制

月度資料趨勢

累計下載1.3萬
360785241.3萬2026-03 · 累計下載 42852026-05 · 累計下載 59292026-06 · 累計下載 67472026-07 · 累計下載 78532026-08 · 累計下載 87562026-09 · 累計下載 1萬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萬—8
2026-088756+11.5%8
2026-077853+16.4%8
2026-066747+13.8%8
2026-055929—8
2026-034285—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萬★ 714Peter Steinberger

wpank 的其他技能

資料月份:2026-10 · 下載/星標數聚合自公開技能註冊庫(ClawHub、SkillHub),按月更新。口徑說明見資料方法。