Community程式設計與開發github.com

alfathafp/portofolio-web-design

簡化程式碼以提升清晰度。用於重構程式碼,使其更清晰而不改變行為。當程式碼可運作但難以閱讀、維護或擴展時使用。用於審查已累積不必要複雜性的程式碼時。

portofolio-web-design 是什麼?

此技能指導 AI 編碼代理如何有系統地簡化程式碼,同時保留其行為。它提供了一個與模型無關的流程,適用於任何 AI 編碼工具(如 Claude Code、Cursor、Codex 等)。核心重點在於降低複雜性,而非減少行數——目標是讓程式碼更易於閱讀、理解、修改和除錯。技能基於五項原則:精確保留行為、遵循專案慣例、以清晰度優先於機巧、維持平衡(避免過度簡化)以及將範圍限制在最近修改的程式碼。它還包括了語言特定的指引(TypeScript/JavaScript、Python、React/JSX)和一個結構化的四步驟簡化流程:先理解再動手(切斯特頓圍欄)、識別簡化機會、逐步應用變更,最後驗證結果。此技能對於處理或審查擁有累積技術債、重複邏輯或深層巢狀結構之程式碼庫的開發者或 AI 代理特別有用。

相容平台✓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. 將範圍限制在變更處

預設只簡化最近修改的程式碼。除非明確要求擴大範圍,否則避免對不相關的程式碼進行順便重構。未限定的簡化會造成差異雜訊,並有引入意外回歸的風險。

簡化流程

第一步:先理解再動手(切斯特頓圍欄)

在變更或移除任何東西之前,先理解它為何存在。這就是切斯特頓圍欄:如果你看到路上有一個圍欄但不理解它為何存在,不要拆除它。先理解原因,然後再決定這個原因是否仍然適用。

在簡化之前,回答:
- 這段程式碼的職責是什麼?
- 誰呼叫它?它又呼叫誰?
- 邊界情況和錯誤路徑是什麼?
- 是否有測試定義了預期的行為?
- 它為什麼可能被這樣寫?(效能?平台限制?歷史原因?)
- 檢查 git blame:這段程式碼的原始上下文是什麼?

如果你無法回答這些問題,你還沒有準備好要簡化。先閱讀更多上下文。

第二步:識別簡化機會

掃描這些模式——每一種都是一個具體的信號,而非模糊的氣味:

結構性複雜度:

模式信號簡化方式
深度巢狀(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 但同時修改狀態的函式重新命名以反映實際行為
解釋「做什麼」的註解// increment counter 在 count++ 上方刪除註解——程式碼已經夠清楚
解釋「為什麼」的註解// Retry because the API is flaky under load保留這些——它們承載了程式碼無法表達的意圖

冗餘:

模式信號簡化方式
重複的邏輯多處出現相同的5行以上提取為共享函式
死程式碼無法到達的分支、未使用的變數、註解掉的區塊移除(在確認確實為死程式碼後)
不必要的抽象沒有增加價值的包裝器內聯包裝器,直接呼叫底層函式
過度設計的模式工廠的工廠、只有一個策略的策略模式替換為簡單直接的方式
冗餘的型別斷言將型別轉換為已推斷的型別移除斷言

第三步:逐步應用變更

一次只進行一個簡化。每次變更後執行測試。將重構變更與功能或錯誤修復變更分開提交。 一個 PR 同時包含重構和新增功能,本質上是兩個 PR——請將它們分開。

對於每個簡化:
1. 進行變更
2. 執行測試套件
3. 如果測試通過 → 提交(或繼續下一個簡化)
4. 如果測試失敗 → 還原並重新考慮

避免將多個簡化批次處理成一個未經測試的變更。如果出了問題,你需要知道是哪個簡化造成的。

500 行規則: 如果重構會觸及超過 500 行程式碼,請投資自動化(codemods、sed 腳本、AST 轉換),而不是手動進行變更。在此規模下手動編輯容易出錯且審查起來很累人。

第四步:驗證結果

完成所有簡化後,退一步評估整體:

比較前後:
- 簡化後的版本是否確實更容易理解?
- 你是否引入了任何與程式碼庫不一致的新模式?
- diff 是否乾淨且可審查?
- 團隊成員會批准這項變更嗎?

如果「簡化後」的版本更難理解或審查,請還原。並非每次簡化嘗試都會成功。

語言特定指引

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

// 簡化:透過中間元件進行 Prop 鑽遞
// 之前 — 考慮 context 或組合是否能更好地解決這個問題。
// 這是一個判斷問題——標記它,不要自動重構。

常見的合理化說詞

合理化說詞現實
「它運作正常,不需要動它」可運作但難以閱讀的程式碼,在出問題時會難以修復。現在簡化可以為將來的每一次變更省下時間。
「行數越少總是越簡單」一個一行的巢狀三元運算並不會比一個五行的 if/else 更簡單。簡潔在於理解速度,而非行數。
「我順便很快地簡化這個不相關的程式碼也無妨」未限定的簡化會產生雜訊般的 diff,並有在你無意變更的程式碼中引入回歸的風險。保持專注。
「型別讓它自我文件化」型別記錄的是結構,而非意圖。一個命名良好的函式在解釋「為什麼」方面,比型別簽名解釋「做什麼」更好。
「這個抽象以後可能會有用」不要保留推測性的抽象。如果現在沒用到,它就是沒有價值的複雜性。移除它,需要時再重新加入。
「原始作者一定有他的理由」也許。檢查 git blame——應用切斯特頓圍欄。但累積的複雜性通常沒有理由;它只是在時間壓力下迭代的殘留物。
「我在添加這個功能時順便重構」將重構與功能工作分開。混合的變更更難審查、還原以及在歷史中理解。

紅旗

  • 需要修改測試才能通過的簡化(你很可能改變了行為)
  • 「簡化後」的程式碼比原始版本更長、更難跟蹤
  • 根據你的偏好而非專案慣例重新命名
  • 因為「它讓程式碼更乾淨」而移除錯誤處理
  • 簡化你還未完全理解的程式碼
  • 將多個簡化批次處理成一個大型、難以審查的提交
  • 重構超出當前任務範圍的程式碼(未經要求)

驗證

完成一輪簡化後:

  • 所有現有測試在無修改的情況下通過
  • 建置成功,無新增警告
  • Linter/formatter 通過(無風格回歸)
  • 每個簡化都是一個可審查、漸進的變更
  • diff 是乾淨的——沒有混入不相關的變更
  • 簡化後的程式碼遵循專案慣例(對照 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.

相關技能