Community编程与开发github.com

代码简化

简化代码以提高可读性,同时不改变行为。适用于代码可以工作但难以阅读、维护或扩展的情况。

代码简化 是什么?

这个技能“代码简化”旨在帮助AI编码代理(如Claude Code、Cursor、Codex等)系统性地降低代码复杂度,同时严格保留原有行为。它基于一套明确的何时使用(功能完成后、代码审查时、遇到深层嵌套时)以及何时不应使用(代码已清晰、不理解代码意图、性能关键区域)的原则。核心流程包含五个原则:精确保留行为、遵循项目规范、优先清晰而非取巧、维持平衡(避免过度简化)、以及聚焦于最近修改的代码范围。它提供了一个结构化的四步过程:理解前不触犯(Chesterton's Fence)、识别简化机会(基于具体的结构性、命名和冗余模式信号)、增量应用更改(每次一个简化,运行测试,遵守“500行法则”)、以及验证结果。该技能涵盖了TypeScript/JavaScript、Python和React/JSX的具体代码示例,并讨论了常见的错误理由和危险信号,以确保简化工作真正降低认知负荷,而不是增加噪音。

兼容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/alfathafp/portofolio-web-design/tree/HEAD/.agents/skills/code-simplification

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

代码简化 是做什么的?

灵感来自 Claude Code Simplifier 插件。在此改编为一种模型无关、以流程驱动的技能,适用于任何 AI 编码代理。

概述

通过降低复杂度来简化代码,同时严格保留原有行为。目标不是更少的行数——而是使代码更易于阅读、理解、修改和调试。每一次简化都必须通过一个简单的测试:“新团队成员理解这个的速度会比原版更快吗?”

何时使用

  • 功能已经能工作且测试通过,但实现方式感觉比需要的更重
  • 在代码审查期间,当可读性或复杂性问题被标记出来时
  • 遇到深层嵌套逻辑、长函数或含义不清的名称时
  • 重构在时间压力下编写的代码时
  • 整合分散在多个文件中的相关逻辑时
  • 合并引入重复或不一致性的更改之后

何时不应使用:

  • 代码已经清晰且可读——不要为了简化而简化
  • 你还不理解代码的功能——在简化之前先理解
  • 代码对性能至关重要,并且“更简单”的版本会明显变慢
  • 你即将完全重写该模块——简化将被废弃的代码是浪费精力

五项原则

1. 精确保留行为

不要改变代码的功能——只改变其表达方式。所有输入、输出、副作用、错误行为和边界情况必须完全相同。如果你不确定某个简化是否保留了行为,就不要做。

每次修改前都要问自己:
→ 对于每个输入,这会生成相同的输出吗?
→ 这能保持相同的错误行为吗?
→ 这能保留相同的副作用和操作顺序吗?
→ 所有现有测试都能无需修改地通过吗?

2. 遵循项目规范

简化意味着使代码与代码库更加一致,而不是强加外部偏好。在简化之前:

1. 阅读 CLAUDE.md / 项目规范
2. 研究相邻代码如何处理类似模式
3. 匹配项目的风格,涉及:
   - 导入顺序和模块系统
   - 函数声明风格
   - 命名约定
   - 错误处理模式
   - 类型注解深度

破坏项目一致性的简化不是简化——而是折腾。

3. 优先清晰而非取巧

当紧凑版本需要脑力停顿才能解析时,显式代码优于紧凑代码。

// 不清晰:密集的三元链
const label = isNew ? 'New' : isUpdated ? 'Updated' : isArchived ? 'Archived' : 'Active';

// 清晰:可读的映射
function getStatusLabel(item: Item): string {
  if (item.isNew) return 'New';
  if (item.isUpdated) return 'Updated';
  if (item.isArchived) return 'Archived';
  return 'Active';
}
// 不清晰:链式 reduce 配合内联逻辑
const result = items.reduce((acc, item) => ({
  ...acc,
  [item.id]: { ...acc[item.id], count: (acc[item.id]?.count ?? 0) + 1 }
}), {});

// 清晰:命名的中间步骤
const countById = new Map<string, number>();
for (const item of items) {
  countById.set(item.id, (countById.get(item.id) ?? 0) + 1);
}

4. 维持平衡

简化有一个失败模式:过度简化。警惕这些陷阱:

  • 过于激进地内联——移除一个为概念命名的辅助函数会使调用处更难阅读
  • 合并不相关的逻辑——将两个简单函数合并成一个复杂函数并不更简单
  • 移除“不必要的”抽象——某些抽象的存在是为了可扩展性或可测试性,而非复杂度
  • 优化行数——减少行数不是目标;更容易理解才是

5. 限定范围

默认只简化最近修改的代码。除非明确要求扩大范围,否则避免对被无关的代码进行间接重构。无范围限制的简化会造成差异噪音,并增加意外回归的风险。

简化流程

步骤 1:先理解,再动手(Chesterton's Fence)

在更改或移除任何东西之前,先理解它为什么存在。这就是Chesterton's Fence:如果你看到路上有一道栅栏,不明白它为什么在那里,就不要把它推倒。首先理解原因,然后再决定这个原因是否仍然适用。

在简化之前,请回答:
- 这段代码的职责是什么?
- 谁调用它?它调用谁?
- 边界情况和错误路径是什么?
- 是否有测试定义了预期的行为?
- 它可能为什么以这种方式编写?(性能?平台限制?历史原因?)
- 检查 git blame:这段代码的原始上下文是什么?

如果你无法回答这些问题,你还没有准备好简化。先阅读更多上下文。

步骤 2:识别简化机会

扫描这些模式——每一种都是具体信号,而非模糊的味道:

结构复杂度:

模式信号简化方法
深层嵌套(3级以上)难以跟踪控制流将条件提取为卫语句或辅助函数
长函数(50行以上)多个职责拆分为职责明确、名称描述性的函数
嵌套三元需要脑内栈来解析替换为 if/else 链、switch 或查找对象
布尔参数标志doThing(true, false, true)替换为选项对象或单独的函数
重复的条件判断在多个地方使用相同的 if 检查提取为一个命名得当的谓词函数

命名与可读性:

模式信号简化方法
通用名称data, result, temp, val, item重命名以描述内容:userProfile, validationErrors
缩写名称usr, cfg, btn, evt除非缩略词是通用的(id, url, api),否则使用完整词汇
误导性名称名为 get 的函数同时修改状态重命名以反映实际行为
解释“什么”的注释// 增加计数器 在 count++ 之上删除注释——代码已经足够清晰
解释“为什么”的注释// 重试是因为 API 在负载下不稳定保留这些——它们承载着代码无法表达的意图

冗余:

模式信号简化方法
重复的逻辑在多个地方存在相同的5行以上代码提取为共享函数
死代码不可达的分支、未使用的变量、被注释的块移除(在确认其确实已死后)
不必要的抽象没有增加价值的包装器内联包装器,直接调用底层函数
过度设计的模式工厂的工厂、只有一个策略的策略替换为简单的直接方法
冗余的类型断言强制转换为已经推断出的类型移除断言

步骤 3:增量应用更改

一次只做一个简化。每次更改后运行测试。将重构更改与功能或错误修复更改分开提交。 一个同时进行重构和添加功能的 PR 应该拆分成两个 PR。

针对每一个简化:
1. 进行更改
2. 运行测试套件
3. 如果测试通过 → 提交(或继续下一个简化)
4. 如果测试失败 → 回滚并重新考虑

避免将多个简化打包成一个未经测试的更改。如果出了问题,你需要知道是哪个简化导致的。

500 行法则: 如果一个重构会影响超过 500 行代码,请投资自动化(codemod、sed 脚本、AST 转换),而不是手动更改。这种规模的手动编辑容易出错并且审查起来非常累人。

步骤 4:验证结果

在所有简化完成后,退后一步评估整体:

比较前后:
- 简化后的版本是否真的更容易理解?
- 你是否引入了任何与代码库不一致的新模式?
- 差异是否清晰且易于审查?
- 团队成员会批准这个更改吗?

如果“简化”后的版本更难理解或审查,请回滚。并非每次简化尝试都会成功。

特定语言指导

TypeScript / JavaScript

// 简化:不必要的 async 包装器
// 之前
async function getUser(id: string): Promise<User> {
  return await userService.findById(id);
}
// 之后
function getUser(id: string): Promise<User> {
  return userService.findById(id);
}

// 简化:冗长的条件赋值
// 之前
let displayName: string;
if (user.nickname) {
  displayName = user.nickname;
} else {
  displayName = user.fullName;
}
// 之后
const displayName = user.nickname || user.fullName;

// 简化:手动构建数组
// 之前
const activeUsers: User[] = [];
for (const user of users) {
  if (user.isActive) {
    activeUsers.push(user);
  }
}
// 之后
const activeUsers = users.filter((user) => user.isActive);

// 简化:冗余的布尔返回
// 之前
function isValid(input: string): boolean {
  if (input.length > 0 && input.length < 100) {
    return true;
  }
  return false;
}
// 之后
function isValid(input: string): boolean {
  return input.length > 0 && input.length < 100;
}

Python

# 简化:冗长的字典构建
# 之前
result = {}
for item in items:
    result[item.id] = item.name
# 之后
result = {item.id: item.name for item in items}

# 简化:嵌套条件配合提前返回
# 之前
def process(data):
    if data is not None:
        if data.is_valid():
            if data.has_permission():
                return do_work(data)
            else:
                raise PermissionError("No permission")
        else:
            raise ValueError("Invalid data")
    else:
        raise TypeError("Data is None")
# 之后
def process(data):
    if data is None:
        raise TypeError("Data is None")
    if not data.is_valid():
        raise ValueError("Invalid data")
    if not data.has_permission():
        raise PermissionError("No permission")
    return do_work(data)

React / JSX

// 简化:冗长的条件渲染
// 之前
function UserBadge({ user }: Props) {
  if (user.isAdmin) {
    return <Badge variant="admin">Admin</Badge>;
  } else {
    return <Badge variant="default">User</Badge>;
  }
}
// 之后
function UserBadge({ user }: Props) {
  const variant = user.isAdmin ? 'admin' : 'default';
  const label = user.isAdmin ? 'Admin' : 'User';
  return <Badge variant={variant}>{label}</Badge>;
}

// 简化:通过中间组件的属性传递
// 之前 —— 考虑 context 或组合是否能更好地解决这个问题。
// 这是一个判断问题——标记它,不要自动重构。

常见合理化借口

合理化借口现实
“它能工作,没必要碰它”能工作但难以阅读的代码在出问题时将难以修复。现在简化可以节省将来每次更改的时间。
“行数越少总是越简单”一行的嵌套三元并不比五行的 if/else 简单。简单是关于理解速度,而不是行数。
“我顺便也快速简化一下这个无关的代码”无范围限制的简化会产生嘈杂的差异,并增加你在无意修改的代码中引入回归的风险。保持专注。
“类型让它自文档化”类型记录了结构,而非意图。一个命名得当的函数解释为什么,比类型签名解释什么更好。
“这个抽象以后可能有用”不要保留投机的抽象。如果现在没用到,那就是没有价值的复杂度。移除它,在需要时再重新添加。
“原始作者一定有他的理由”也许吧。检查 git blame —— 应用 Chesterton's Fence。但累积的复杂度往往没有理由;它只是在压力下迭代的残留物。
“我在添加这个功能的同时重构”将重构与功能工作分开。混合的更改更难审查、回滚和在历史中理解。

危险信号

  • 需要修改测试才能通过的简化(你可能改变了行为)
  • “简化”后的代码比原版更长且更难理解
  • 根据你的偏好而不是项目规范重命名东西
  • 因为“会使代码更干净”而移除错误处理
  • 简化你并不完全理解的代码
  • 将多个简化打包成一个难以审查的大提交
  • 在未经要求的情况下重构当前任务范围之外的代码

验证

完成一轮简化后:

  • 所有现有测试无需修改即可通过
  • 构建成功,无新警告
  • Linter/formatter 通过(无风格回归)
  • 每个简化都是一个可审查、增量的更改
  • 差异是干净的——没有混合无关的更改
  • 简化后的代码遵循项目规范(已对照 CLAUDE.md 或等效文件检查)
  • 没有移除或弱化错误处理
  • 没有留下死代码(未使用的导入、不可达的分支)
  • 团队成员或审查代理会批准此更改,认为其是净改进

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

alfathafp/portofolio-web-design

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).

alfathafp/portofolio-web-design

Tests in real browsers via Chrome DevTools MCP. Use when building or debugging anything that runs in a browser. Use when you need to inspect the DOM, capture console errors, analyze network requests, profile performance, or verify visual output with real runtime data. Requires the chrome-devtools MCP server to be configured.

alfathafp/portofolio-web-design

Automates CI/CD pipeline setup. Use when setting up or modifying build and deployment pipelines. Use when you need to automate quality gates, configure test runners in CI, or establish deployment strategies.

alfathafp/portofolio-web-design

Conducts multi-axis code review. Use before merging any change. Use when reviewing code written by yourself, another agent, or a human. Use when you need to assess code quality across multiple dimensions before it enters the main branch. Use when asked to review a diff or a pull request, even when the diff is pasted inline.

alfathafp/portofolio-web-design

Establishes a project's quality bar as a written contract and stops agents quietly lowering it. Interviews the user on which dimensions matter, supplies sane default thresholds when they have no number in mind, records everything in CONSTRAINTS.md, and watches the diff for a weakened bar — new @ts-ignore or eslint-disable suppressions, skipped or deleted tests, assertions stripped out, unimplemented stubs, thresholds edited down. Use when no quality bar is written down, when the user says "set up constraints" or "define our standards", when the user wants dimensions they care about — accessibility, web performance, coverage — set up as enforced constraints, when an agent keeps silencing checks or skipping tests to get to green, when you need a coverage or performance threshold and don't know what number to pick, or when an agent writes more code than anyone will read.

alfathafp/portofolio-web-design

Optimizes agent context setup. Use when starting a new session, when agent output quality degrades, when switching between tasks, or when you need to configure rules files and context for a project.

alfathafp/portofolio-web-design

Guides systematic root-cause debugging. Use when tests fail, builds break, something that worked yesterday broke, behavior doesn't match expectations, or you encounter any unexpected error. Use when you need to figure out what broke and why — a systematic approach to finding and fixing the root cause rather than guessing.

alfathafp/portofolio-web-design

Deploy applications and websites to Vercel. Use when the user requests deployment actions like "deploy my app", "deploy and give me the link", "push this live", or "create a preview deployment".

alfathafp/portofolio-web-design

Manages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to maintain or sunset existing code.

alfathafp/portofolio-web-design

Use when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.

alfathafp/portofolio-web-design

Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies

alfathafp/portofolio-web-design

Records decisions and documentation. Use when you need to document an architecture decision (ADR) or the reasoning behind a design choice, when changing public APIs, shipping features, or when you need to record context that future engineers and agents will need to understand the codebase.

alfathafp/portofolio-web-design

Subjects every non-trivial decision to a fresh-context adversarial review before it stands. Use when you want every assumption cross-examined before proceeding, when stress-testing a plan for hidden failure modes, when correctness matters more than speed, when working in unfamiliar code, when stakes are high (production auth, security-sensitive logic, a high-stakes migration, irreversible operations), or any time a confident output would be cheaper to verify now than to debug later.

alfathafp/portofolio-web-design

Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available

alfathafp/portofolio-web-design

Use when implementation is complete, all tests pass, and you need to decide how to integrate the work

alfathafp/portofolio-web-design

Builds production-quality, accessible, responsive user-facing UIs. Use when building or modifying interfaces and pages, creating components, implementing layouts, meeting WCAG accessibility requirements, managing state, or when the output needs to look and feel production-quality rather than AI-generated.

alfathafp/portofolio-web-design

Structures git workflow practices. Use when making any code change. Use when committing, branching, resolving conflicts, splitting uncommitted work in a messy working tree into clean atomic commits, opening or reviewing a pull request (PR), pushing to a remote, or when you need to organize work across multiple parallel streams. Use when cutting a release, choosing a semantic version bump, tagging, or writing a changelog.

alfathafp/portofolio-web-design

Refines raw ideas into sharp, actionable concepts through structured divergent and convergent thinking. Use when an idea is still vague, when you need to stress-test assumptions before committing to a plan, or when you want to expand options before converging on one. Triggers on "ideate", "refine this idea", or "stress-test my plan".

alfathafp/portofolio-web-design

Delivers changes incrementally in thin, verifiable slices. Use when implementing any feature or change that touches more than one file, or when picking up the next task from a plan. Use when rolling a change out behind a feature flag, when you're about to write a large amount of code at once, or when a task feels too big to land in one step.

alfathafp/portofolio-web-design

Guides stable API and interface design. Use when designing APIs, module boundaries, or any public interface. Use when creating REST or GraphQL endpoints, defining type contracts between modules, or establishing boundaries between frontend and backend.

相关技能