AgentSkillsCN

clean-code

遵循Clean Code原则编写整洁、可维护和易读代码的指南。当审查代码质量、重构、命名变量/函数、提高可读性、降低复杂度,或用户提及代码异味、技术债务、可维护性或要求改进代码质量时使用。

SKILL.md
--- frontmatter
name: clean-code
version: 2.0.0
description: Guide for writing clean, maintainable, and readable code following Clean Code principles. Use when reviewing code quality, refactoring, naming variables/functions, improving readability, reducing complexity, or when user mentions code smells, technical debt, maintainability, or asks for code quality improvements.
allowed-tools: Read, Grep, Glob, Edit, Write
triggers: [
  "clean code", "code quality", "readable code", "maintainable code",
  "refactor", "refactoring", "code smell", "code smells",
  "naming", "variable names", "function names", "meaningful names",
  "comments", "commenting", "documentation",
  "function size", "method length", "too long", "complex function",
  "cyclomatic complexity", "cognitive complexity",
  "DRY", "don't repeat yourself", "duplication", "duplicate code",
  "KISS", "keep it simple",
  "YAGNI", "you aren't gonna need it",
  "magic numbers", "magic strings", "constants",
  "nested if", "nested loops", "deeply nested",
  "single responsibility", "does too much",
  "code review", "review code quality",
  "technical debt", "legacy code", "unreadable code",
  "boy scout rule", "leave it cleaner",
  "async await", "concurrency", "thread safety"
]

Clean Code Development Guide

This skill helps you write clean, maintainable, and readable code following Robert C. Martin's (Uncle Bob) Clean Code principles.

"Clean code is simple and direct. Clean code reads like well-written prose." — Grady Booch

Quick Links

DocumentDescription
CHECKLIST.mdCode review checklist
PRINCIPLES.mdIndex of all principles
ExamplesC# code examples
Metrics & ToolsCode quality measurement
Decision TreesVisual decision guides

When to Use This Skill

  • Reviewing code for quality issues
  • Refactoring existing code for better readability
  • Improving naming conventions
  • Simplifying complex functions
  • Reducing code duplication
  • Eliminating code smells
  • Writing self-documenting code
  • Reducing technical debt

Relationship with Clean Architecture

AspectClean CodeClean Architecture
FocusMicro-levelMacro-level
ScopeFunctions, classes, namingLayers, dependencies, modules
GoalReadable, maintainable codeFlexible, testable systems

Use both together: Clean Architecture provides structure; Clean Code ensures each piece is well-written.

See: Clean Architecture Skill


Core Principles Overview

1. Meaningful Names

Names should reveal intent, avoid disinformation, and be pronounceable.

RuleBadGood
Reveal intentint dint elapsedDays
Avoid abbreviationsstring custNmstring customerName
Class names = nounsclass Processclass OrderProcessor
Method names = verbsvoid Order()void PlaceOrder()
Booleans = predicatesbool flagbool isActive

2. Functions

Functions should be small, do one thing, and have minimal parameters.

MetricTarget
Lines5-20 (max 30)
Parameters0-2 (max 3)
Levels of abstraction1 per function
Nesting depthMax 2 levels

Key rules:

  • Do ONE thing
  • No side effects
  • Command-Query Separation
  • Prefer exceptions to error codes

3. Comments

Good code is self-documenting. Comments should explain WHY, not WHAT.

✅ Acceptable comments:

  • Legal/copyright notices
  • Intent explanation
  • Warning of consequences
  • TODO with ticket references
  • Public API documentation

❌ Delete these:

  • Redundant comments
  • Commented-out code
  • Journal/changelog comments
  • Closing brace comments

4. Formatting

Code formatting is about communication.

MetricTargetMax
File size~200 lines500
Line width80-100 chars120

Rules:

  • Vertical: Related code close together
  • Horizontal: Consistent indentation
  • Team: Agree on standards and enforce with tools

5. Objects vs Data Structures

AspectObjectsData Structures
DataHiddenExposed
BehaviorRich methodsNone
Use caseDomain entitiesDTOs

Law of Demeter: Don't talk to strangers. Avoid a.GetB().GetC().DoSomething().

6. Error Handling

Errors should be handled gracefully without obscuring logic.

Key rules:

  • Use exceptions, not error codes
  • Provide context in exceptions
  • Don't return null → use Null Object, Option, or throw
  • Don't pass null
  • Wrap third-party exceptions

7. Boundaries

Manage third-party code with wrappers and adapters.

  • Wrap third-party APIs in adapters
  • Use interfaces you control
  • Write learning tests for third-party code
  • Convert to domain types at boundaries

8. Unit Tests

Test code is just as important as production code.

F.I.R.S.T.:

  • Fast
  • Independent
  • Repeatable
  • Self-validating
  • Timely

Key rules:

  • One concept per test
  • Arrange-Act-Assert pattern
  • Test edge cases
  • Don't test private methods

9. Classes

Classes should be small and have single responsibility.

MetricTarget
Responsibilities1
Public methods5-10 max
Lines100-200 typical
Dependencies3-5 max

Key rules:

  • Single Responsibility Principle
  • High cohesion
  • Depend on abstractions
  • Avoid "Manager", "Handler", "Processor" names

10. Emergence

Kent Beck's four rules of simple design (in priority order):

  1. Runs all tests — System must be verifiable
  2. No duplication — DRY principle
  3. Expresses intent — Self-documenting code
  4. Minimal elements — No unnecessary complexity

11. Concurrency

Writing clean concurrent code requires special care.

Key rules:

  • Separate concurrency from business logic
  • Minimize shared mutable state
  • Use immutable objects
  • Async/await all the way
  • Support cancellation
  • Avoid deadlocks with consistent lock ordering

12. Smells & Heuristics

Comprehensive catalog of code smells from Clean Code Appendix B.

Categories: Comments (C), Environment (E), Functions (F), General (G), Names (N), Tests (T)


Quick Decision Tree

code
Is this code hard to understand?
├─ Bad naming? → Rename to reveal intent
├─ Too long? → Extract smaller pieces
├─ Too complex? → Simplify logic, reduce nesting
├─ Duplicated? → Extract to shared method
└─ Needs comments? → Refactor until self-documenting

Is this function doing too much?
├─ Multiple abstraction levels? → Extract methods
├─ Multiple responsibilities? → Split into focused functions
├─ Too many parameters? → Create parameter object
└─ Side effects? → Separate commands from queries

Is this class too large?
├─ Multiple reasons to change? → Split by responsibility (SRP)
├─ Too many dependencies? → Review architecture
└─ Hard to test? → Apply Dependency Inversion

Code Quality Metrics

MetricTargetTool
Cyclomatic Complexity< 10/methodRoslyn Analyzers
Code Coverage> 80% business logicdotnet test
Maintainability Index> 70SonarQube
Line Length< 120 charsEditorConfig

The Boy Scout Rule

"Leave the code cleaner than you found it."

When touching code, always:

  • Fix bad names
  • Extract long methods
  • Remove duplication
  • Delete commented code
  • Simplify complex expressions

Language-Specific Examples

C# / .NET


Working with This Skill

When I use this skill, I will:

  1. Analyze code for quality issues
  2. Identify code smells and anti-patterns
  3. Suggest concrete refactorings
  4. Apply clean code principles
  5. Ensure code remains testable and maintainable
  6. Reference Clean Architecture when structural issues are found

Reference Materials

Books:

  • Clean Code by Robert C. Martin
  • Refactoring by Martin Fowler
  • Code Complete by Steve McConnell