微算力 · API 导航与自营网关
API 接入 EN
未登录登录
🧹

编写可读可维护代码的实战规范

Clean Code · v1.0.0
专业技能 安全 A 级 作者 wpank 公开目录收录
4.5k 下载 6 安装 18.7k 收藏 67 浏览

简介

软件工程经典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.

通过你的 Agent 添加

安装目录:clean-code/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。

点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。

或者手动安装

Claude Code~/.claude/skills/clean-code-9438/
Codex CLI~/.codex/skills/clean-code-9438/
DeepSeek Harness~/.agents/skills/clean-code-9438/

包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可; 目录名不用换,也不要把包直接解压到 skills 根目录。 技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。

中文使用说明 来自收录源

Clean Code:专业级代码整洁指南

clean-code 是由个人开发者 wpank(Wolfgang Pankratz)发布的一款纯文档型 Agent Skill,致力于将「代码整洁之道」的核心原则落地为 AI 编码助手可遵循的实操规范。该 Skill 以 Markdown 文档为载体,涵盖了命名规则、函数设计、代码结构、反模式目录、重构模式库以及编辑前安全检查清单等六大模块,为开发者在编写新代码、重构旧代码或审查代码质量时提供即时、明确的标准参考。

核心用法

该 Skill 本质上是一套结构化的编码最佳实践知识库。它围绕「简洁、直接、聚焦解决方案」的理念,提供了具体的规则和代码示例。核心功能包括:锁死命名规范(如布尔值必须以 is/has/can 开头)、强制执行函数体不超过 20 行、禁止超过 2 层嵌套、杜绝魔法数字、要求在编辑文件前检查其依赖关系。其内置的「Pre-Edit Safety Check」能强制 Agent 在修改代码前回答四个关键问题,最大限度避免因修改共享组件或接口而引发的连锁故障。

显著优点

  1. 零风险、高度安全:根据 CLS-Certify v2.1.0 的安全认证报告,该 Skill 为纯静态文档,零可执行代码、零外部依赖、零网络请求、零数据收集,是极其罕见的「全透明」技能,不存在供应链攻击、远程代码执行或隐私泄露风险。
  2. 立即可用,规则明确:所有规则均配有「Bad/Good」代码对比示例,且对于反模式、代码坏味道等有专门的参考目录,Agent 可直接调用这些具体规则来指导代码生成或提供修改建议,无需模糊的推测。
  3. 强化工程纪律:通过 8 条「NEVER DO」铁律(如绝不遗留注释掉的代码、绝不创建少于 3 个用例的抽象),可以有效约束 Agent 的产出质量,使其生成的代码天然符合可维护性标准。

潜在缺点或局限性

  1. 非原生可执行逻辑:该 Skill 是知识指南,而不是一个能自动执行代码格式化或重构的工具。其效果完全依赖于 Agent 对规则的理解和执行力度,缺乏自动化的强制力。
  2. T3 来源的信任度限制:因来自个人开发者,其权威性和长期维护承诺不如由知名组织(如 Airbnb、Google)发布的等效规范。虽然内容透明,但在高度受管制的企业环境中,可能需要内部评审才能推广使用。
  3. 上下文占用:包含大量规则和示例的完整文档可能占用一定的上下文窗口。对于简单任务,加载全套规范是一种资源浪费,但在复杂多文件重构任务中,这些细节又至关重要。

适合的目标群体

该 Skill 非常适合追求代码质量的个人开发者、小型敏捷团队以及将 AI 编程助手用作结对编程伙伴的工程师。对于正在试图统一团队编码标准但尚未建立完整文档体系的技术负责人,该 Skill 可以作为一套现成且论证充分的起步规范,直接嵌入到 Agent 工作流中,让 AI 助手成为标准的忠实执行者和推广者。此外,编程初学者可以通过观察 Agent 基于此规范的产出,耳濡目染地养成好的编码习惯。

常规使用风险

最大风险在于误用:用户可能期望它是能自动运行 prettier 或 eslint 的工具。实际上,它是一个知识性的「提示词系统」,旨在增强 Agent 的判断力,而非替代代码静态分析工具。另一个风险是代码风格法西斯主义——过度追求「小函数」和「最优命名」可能导致过度工程化,反而降低开发效率。最后,尽管当前版本绝对安全,但因其来自个人维护者(T3),未来版本若引入可执行脚本或外部依赖,用户必须重新进行安全评估。建议将该 Skill 的版本固定在经过审计的 1.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

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

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

正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。

标签

clean-codecode-qualityrefactoringnaming-conventionsbest-practicessoftware-engineeringmaintainability

同类 Skill