Clean Code

作者 davila78da17d671b6f無授權條款32K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫今天更新

Pragmatic coding standards - concise, direct, no over-engineering, no unnecessary comments

AI 產生的概覽

給 AI 代理的務實編碼規範:程式碼精簡、命名清楚、函式短小,並在編輯前檢查相依性。

功能
此技能為撰寫或修改軟體的 AI 代理提供一套編碼規範與規則。內容涵蓋單一職責、DRY、KISS、YAGNI 等核心原則,以及命名慣例、函式長度限制、程式碼結構模式與應避免的反模式。它也要求代理在編輯前檢查相依檔案,並在宣告任務完成前進行自我檢查。
適用情境
適用於 AI 代理撰寫、修改或審查程式碼,且需要遵循一致務實標準的情境。適合偏好精簡直接程式碼、而非解釋或過度設計的實作類任務。
執行需求
不需要腳本或套件,屬於純指令型技能。文中提及外部的驗證腳本與工具(例如以 Python 撰寫的稽核與 lint 腳本),但這些腳本並未隨本技能一併提供。

Clean Code - Pragmatic AI Coding Standards

CRITICAL SKILL - Be concise, direct, and solution-focused.


Core Principles

PrincipleRule
SRPSingle Responsibility - each function/class does ONE thing
DRYDon't Repeat Yourself - extract duplicates, reuse
KISSKeep It Simple - simplest solution that works
YAGNIYou Aren't Gonna Need It - don't build unused features
Boy ScoutLeave code cleaner than you found it

Naming Rules

ElementConvention
VariablesReveal intent: userCount not n
FunctionsVerb + noun: getUserById() not user()
BooleansQuestion form: isActive, hasPermission, canEdit
ConstantsSCREAMING_SNAKE: MAX_RETRY_COUNT

Rule: If you need a comment to explain a name, rename it.


Function Rules

RuleDescription
SmallMax 20 lines, ideally 5-10
One ThingDoes one thing, does it well
One LevelOne level of abstraction per function
Few ArgsMax 3 arguments, prefer 0-2
No Side EffectsDon't mutate inputs unexpectedly

Code Structure

PatternApply
Guard ClausesEarly returns for edge cases
Flat > NestedAvoid deep nesting (max 2 levels)
CompositionSmall functions composed together
ColocationKeep related code close

AI Coding Style

SituationAction
User asks for featureWrite it directly
User reports bugFix it, don't explain
No clear requirementAsk, don't assume

Anti-Patterns (DON'T)

❌ Pattern✅ Fix
Comment every lineDelete obvious comments
Helper for one-linerInline the code
Factory for 2 objectsDirect instantiation
utils.ts with 1 functionPut code where used
"First we import..."Just write code
Deep nestingGuard clauses
Magic numbersNamed constants
God functionsSplit by responsibility

🔴 Before Editing ANY File (THINK FIRST!)

Before changing a file, ask yourself:

QuestionWhy
What imports this file?They might break
What does this file import?Interface changes
What tests cover this?Tests might fail
Is this a shared component?Multiple places affected

Quick Check:

File to edit: UserService.ts└── Who imports this? → UserController.ts, AuthController.ts└── Do they need changes too? → Check function signatures

🔴 Rule: Edit the file + all dependent files in the SAME task. 🔴 Never leave broken imports or missing updates.


Summary

DoDon't
Write code directlyWrite tutorials
Let code self-documentAdd obvious comments
Fix bugs immediatelyExplain the fix first
Inline small thingsCreate unnecessary files
Name things clearlyUse abbreviations
Keep functions smallWrite 100+ line functions

Remember: The user wants working code, not a programming lesson.


🔴 Self-Check Before Completing (MANDATORY)

Before saying "task complete", verify:

CheckQuestion
✅ Goal met?Did I do exactly what user asked?
✅ Files edited?Did I modify all necessary files?
✅ Code works?Did I test/verify the change?
✅ No errors?Lint and TypeScript pass?
✅ Nothing forgotten?Any edge cases missed?

🔴 Rule: If ANY check fails, fix it before completing.


Verification Scripts (MANDATORY)

🔴 CRITICAL: Each agent runs ONLY their own skill's scripts after completing work.

Agent → Script Mapping

AgentScriptCommand
frontend-specialistUX Auditpython ~/.claude/skills/frontend-design/scripts/ux_audit.py .
frontend-specialistA11y Checkpython ~/.claude/skills/frontend-design/scripts/accessibility_checker.py .
backend-specialistAPI Validatorpython ~/.claude/skills/api-patterns/scripts/api_validator.py .
mobile-developerMobile Auditpython ~/.claude/skills/mobile-design/scripts/mobile_audit.py .
database-architectSchema Validatepython ~/.claude/skills/database-design/scripts/schema_validator.py .
security-auditorSecurity Scanpython ~/.claude/skills/vulnerability-scanner/scripts/security_scan.py .
seo-specialistSEO Checkpython ~/.claude/skills/seo-fundamentals/scripts/seo_checker.py .
seo-specialistGEO Checkpython ~/.claude/skills/geo-fundamentals/scripts/geo_checker.py .
performance-optimizerLighthousepython ~/.claude/skills/performance-profiling/scripts/lighthouse_audit.py <url>
test-engineerTest Runnerpython ~/.claude/skills/testing-patterns/scripts/test_runner.py .
test-engineerPlaywrightpython ~/.claude/skills/webapp-testing/scripts/playwright_runner.py <url>
Any agentLint Checkpython ~/.claude/skills/lint-and-validate/scripts/lint_runner.py .
Any agentType Coveragepython ~/.claude/skills/lint-and-validate/scripts/type_coverage.py .
Any agenti18n Checkpython ~/.claude/skills/i18n-localization/scripts/i18n_checker.py .

❌ WRONG: test-engineer running ux_audit.py ✅ CORRECT: frontend-specialist running ux_audit.py


🔴 Script Output Handling (READ → SUMMARIZE → ASK)

When running a validation script, you MUST:

  1. Run the script and capture ALL output
  2. Parse the output - identify errors, warnings, and passes
  3. Summarize to user in this format:
markdown
## Script Results: [script_name.py]
### ❌ Errors Found (X items)- [File:Line] Error description 1- [File:Line] Error description 2
### ⚠️ Warnings (Y items)- [File:Line] Warning description
### ✅ Passed (Z items)- Check 1 passed- Check 2 passed
**Should I fix the X errors?**
  1. Wait for user confirmation before fixing
  2. After fixing → Re-run script to confirm

🔴 VIOLATION: Running script and ignoring output = FAILED task. 🔴 VIOLATION: Auto-fixing without asking = Not allowed. 🔴 Rule: Always READ output → SUMMARIZE → ASK → then fix.

來源與署名

來源:davila7/claude-code-templates位於cli-tool/components/skills/development/clean-code提交8da17d6

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架