clean-code-developer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Clean Code Development

整洁代码开发

Systematic approach to writing clean, maintainable code through software engineering best practices.
通过软件工程最佳实践系统性地编写整洁、可维护代码的方法。

Purpose

目标

Apply SOLID principles, eliminate code duplication, maintain simplicity, and write code that reads like well-written prose.
遵循SOLID原则,消除代码重复,保持简洁性,编写如流畅散文般易读的代码。

When to Use

适用场景

Use this skill when:
  • Code Reviews: Reviewing code for adherence to clean code principles
  • Refactoring: Improving existing code structure and maintainability
  • Coding Standards: Enforcing consistent coding practices and conventions
  • Clean Code Guidance: Seeking advice on clean code principles and patterns
  • Quality Checks: Integrating automated quality checks into workflows
在以下场景使用该技能:
  • 代码审查:检查代码是否符合整洁代码原则
  • 代码重构:改进现有代码的结构与可维护性
  • 编码标准:执行一致的编码实践与规范
  • 整洁代码指导:寻求整洁代码原则与模式的建议
  • 质量检查:在工作流中集成自动化质量检查

Core Principles

核心原则

SOLID Principles

SOLID原则

Single Responsibility Principle

单一职责原则(Single Responsibility Principle)

  • Each function/module has one reason to change
  • Clear, focused purpose
  • Easy to test and maintain
  • 每个函数/模块只有一个修改的理由
  • 清晰、明确的目标
  • 易于测试与维护

Open-Closed Principle

开闭原则(Open-Closed Principle)

  • Open for extension, closed for modification
  • Use interfaces/traits for abstraction
  • New behavior through composition, not modification
  • 对扩展开放,对修改关闭
  • 使用接口/特征(traits)实现抽象
  • 通过组合实现新行为,而非修改现有代码

Liskov Substitution Principle

里氏替换原则(Liskov Substitution Principle)

  • Subtypes must be substitutable for base types
  • Derived classes should enhance functionality
  • Don't break expected behavior
  • 子类型必须能够替换其基类型
  • 派生类应增强功能
  • 不破坏预期行为

Interface Segregation Principle

接口隔离原则(Interface Segregation Principle)

  • Clients shouldn't depend on interfaces they don't use
  • Small, focused interfaces
  • Prefer composition over large interfaces
  • 客户端不应依赖其不需要的接口
  • 小巧、聚焦的接口
  • 优先使用组合而非庞大的接口

Dependency Inversion Principle

依赖倒置原则(Dependency Inversion Principle)

  • Depend on abstractions, not concretions
  • High-level modules shouldn't depend on low-level modules
  • Use dependency injection
  • 依赖抽象而非具体实现
  • 高层模块不应依赖低层模块
  • 使用依赖注入

Other Key Principles

其他关键原则

DRY (Don't Repeat Yourself)

DRY(Don't Repeat Yourself,不要重复自己)

  • Extract common code into reusable functions/modules
  • Avoid duplication through abstraction
  • One source of truth for each piece of logic
  • 将通用代码提取为可复用的函数/模块
  • 通过抽象避免重复
  • 每个逻辑片段只有单一的权威来源

KISS (Keep It Simple, Stupid)

KISS(Keep It Simple, Stupid,保持简单)

  • Simple solutions over complex ones
  • Avoid over-engineering
  • Clear, straightforward code
  • 优先选择简单方案而非复杂方案
  • 避免过度设计
  • 清晰、直接的代码

YAGNI (You Aren't Gonna Need It)

YAGNI(You Aren't Gonna Need It,你不会需要它)

  • Don't build for hypothetical future requirements
  • Implement what's needed now
  • Defer complexity until necessary
  • 不为假设的未来需求构建功能
  • 只实现当前所需的功能
  • 必要时再引入复杂度

Boy Scout Rule

童子军规则(Boy Scout Rule)

  • Leave code better than you found it
  • Small improvements add up
  • Prevent technical debt accumulation
  • 让代码比你接手时更优秀
  • 小改进积累成大提升
  • 防止技术债务累积

Code Quality Assessment

代码质量评估

Readability

可读性

  • Self-documenting code
  • Clear, descriptive names
  • Logical flow
  • Appropriate comments
  • 自文档化代码
  • 清晰、描述性的命名
  • 逻辑流畅
  • 恰当的注释

Maintainability

可维护性

  • Easy to understand
  • Easy to modify
  • Easy to test
  • Clear structure
  • 易于理解
  • 易于修改
  • 易于测试
  • 清晰的结构

Testability

可测试性

  • Dependencies easily mocked
  • Pure functions where possible
  • Clear inputs and outputs
  • Testable in isolation
  • 依赖易于模拟(mock)
  • 尽可能使用纯函数
  • 清晰的输入与输出
  • 可独立测试

Extensibility

可扩展性

  • Open for extension
  • Closed for modification
  • Plugin points where appropriate
  • Flexible design
  • 对扩展开放
  • 对修改关闭
  • 适当设置插件扩展点
  • 灵活的设计

Refactoring Techniques

重构技巧

Extract Method/Function

提取方法/函数

  • Replace duplicated code with method call
  • Name methods by what they do
  • Keep methods small and focused
  • 用方法调用替代重复代码
  • 按功能为方法命名
  • 保持方法小巧、聚焦

Extract Class/Module

提取类/模块

  • Group related functionality
  • Create coherent abstractions
  • Separate concerns
  • 分组相关功能
  • 创建连贯的抽象
  • 分离关注点

Replace Conditional with Polymorphism

用多态替代条件判断

  • Use strategy pattern for conditionals
  • Eliminate type checking
  • Improve extensibility
  • 对条件判断使用策略模式
  • 消除类型检查
  • 提升可扩展性

Introduce Parameter Object

引入参数对象

  • Reduce parameter count
  • Group related parameters
  • Improve method signatures
  • 减少参数数量
  • 分组相关参数
  • 优化方法签名

Decompose Conditional

分解条件判断

  • Simplify complex conditions
  • Extract boolean expressions
  • Improve readability
  • 简化复杂条件
  • 提取布尔表达式
  • 提升可读性

Anti-Patterns to Avoid

需避免的反模式

Code Smells

代码异味

  • Long Method: Break into smaller methods
  • Long Parameter List: Use parameter objects
  • Duplicate Code: Extract to reusable functions
  • Large Class: Split into smaller classes
  • God Class: Reduce responsibilities
  • Feature Envy: Move methods to appropriate classes
  • Data Clumps: Group related data
  • Primitive Obsession: Use value objects
  • Switch Statements: Use polymorphism/strategy pattern
  • Temporary Field: Eliminate through parameter passing
  • Refused Bequest: Pass parameters explicitly
  • 长方法:拆分为更小的方法
  • 长参数列表:使用参数对象
  • 重复代码:提取为可复用函数
  • 大类:拆分为更小的类
  • 上帝类:减少职责范围
  • 特性羡慕:将方法移至合适的类中
  • 数据泥团:分组相关数据
  • 原始类型痴迷:使用值对象
  • Switch语句:使用多态/策略模式
  • 临时字段:通过参数传递消除
  • 被拒绝的继承:显式传递参数

Rust-Specific Issues

Rust特有的问题

  • Excessive Clone: Use borrowing or Arc
  • Unnecessary Unwrap: Use proper error handling with
    ?
  • Deep Nesting: Extract methods to flatten
  • Large Functions: Split into smaller, focused functions (< 50 LOC)
  • Unsafe Code: Only when necessary, well-documented
  • Memory Leaks: Proper ownership and borrowing
  • Deadlocks: Release locks before
    .await
  • 过度克隆(Excessive Clone):使用借用或Arc
  • 不必要的Unwrap:使用
    ?
    进行正确的错误处理
  • 深层嵌套:提取方法以扁平化结构
  • 大函数:拆分为更小、聚焦的函数(少于50行代码)
  • Unsafe代码:仅在必要时使用并做好文档
  • 内存泄漏:正确使用所有权与借用规则
  • 死锁:在
    .await
    前释放锁

Integration with Development Workflows

与开发工作流的集成

Pre-Commit Hooks

提交前钩子(Pre-Commit Hooks)

  • Run formatting (rustfmt)
  • Run linting (clippy)
  • Run basic tests
  • Check for common anti-patterns
  • 运行格式化工具(rustfmt)
  • 运行代码检查(clippy)
  • 运行基础测试
  • 检查常见反模式

CI/CD Integration

CI/CD集成

  • Automated formatting checks
  • Linting with warnings as errors
  • Test coverage requirements
  • Code quality metrics
  • 自动化格式检查
  • 将代码检查警告视为错误
  • 测试覆盖率要求
  • 代码质量指标

Code Review Checklist

代码审查清单

  • Follows SOLID principles
  • No code duplication
  • Appropriate naming conventions
  • Proper error handling
  • Comprehensive tests
  • Clear documentation
  • 遵循SOLID原则
  • 无代码重复
  • 命名规范恰当
  • 错误处理正确
  • 测试全面
  • 文档清晰

Best Practices

最佳实践

DO:

建议:

✓ Apply SOLID principles consistently ✓ Extract common code into reusable functions ✓ Keep functions small and focused (< 50 LOC) ✓ Use descriptive names that reveal intent ✓ Write tests before refactoring (TDD) ✓ Document complex business logic, not obvious code ✓ Use static analysis tools (clippy, SonarQube) ✓ Leave code better than you found it ✓ Prefer composition over inheritance ✓ Keep dependencies minimal and explicit
✓ 持续遵循SOLID原则 ✓ 将通用代码提取为可复用函数 ✓ 保持函数小巧、聚焦(少于50行代码) ✓ 使用能体现意图的描述性命名 ✓ 重构前先编写测试(测试驱动开发TDD) ✓ 仅为复杂业务逻辑编写文档,无需注释明显代码 ✓ 使用静态分析工具(clippy、SonarQube) ✓ 让代码比你接手时更优秀 ✓ 优先使用组合而非继承 ✓ 保持依赖最小化且明确

DON'T:

禁忌:

✗ Violate SOLID principles ✗ Duplicate code "for now" - fix immediately ✗ Write functions longer than 50 lines without strong justification ✗ Use abbreviations or unclear names ✗ Refactor without adequate test coverage ✗ Over-document obvious code ✗ Skip static analysis warnings ✗ Over-engineer simple problems ✗ Create tight coupling between modules
✗ 违反SOLID原则 ✗ 暂时容忍代码重复——立即修复 ✗ 编写超过50行的函数(除非有充分理由) ✗ 使用缩写或不清晰的命名 ✓ 在测试覆盖率不足的情况下进行重构 ✗ 过度注释明显代码 ✗ 忽略静态分析警告 ✗ 对简单问题过度设计 ✗ 模块间创建紧密耦合

Metrics

指标

Track these metrics to assess code quality:
  • Cyclomatic Complexity: Average < 10 per function
  • Lines of Code: < 500 per file (project standard)
  • Function Length: < 50 lines average
  • Test Coverage: > 90% line coverage
  • Code Duplication: < 5%
  • Technical Debt Ratio: Trend downward over time
跟踪以下指标以评估代码质量:
  • 圈复杂度:每个函数平均<10
  • 代码行数:每个文件<500(项目标准)
  • 函数长度:平均少于50行
  • 测试覆盖率:行覆盖率>90%
  • 代码重复率:<5%
  • 技术债务比率:随时间呈下降趋势

Examples

示例

Example 1: Extract Method

示例1:提取方法

rust
// BEFORE - Code smell: duplicate logic
fn process_data_a(data: &Data) -> Result<Output> {
    // Validation
    if data.id.is_empty() {
        return Err(anyhow!("ID is required"));
    }
    if data.value < 0 {
        return Err(anyhow!("Value must be positive"));
    }
    // Processing
    let result = calculate(data);
    Ok(result)
}

fn process_data_b(data: &Data) -> Result<Output> {
    // Same validation code duplicated
    if data.id.is_empty() {
        return Err(anyhow!("ID is required"));
    }
    if data.value < 0 {
        return Err(anyhow!("Value must be positive"));
    }
    // Processing
    let result = calculate(data);
    Ok(result)
}
rust
// AFTER - Applied DRY principle
fn validate_data(data: &Data) -> Result<()> {
    if data.id.is_empty() {
        return Err(anyhow!("ID is required"));
    }
    if data.value < 0 {
        return Err(anyhow!("Value must be positive"));
    }
    Ok(())
}

fn process_data_a(data: &Data) -> Result<Output> {
    validate_data(data)?;
    let result = calculate(data);
    Ok(result)
}

fn process_data_b(data: &Data) -> Result<Output> {
    validate_data(data)?;
    let result = calculate(data);
    Ok(result)
}
rust
// BEFORE - Code smell: duplicate logic
fn process_data_a(data: &Data) -> Result<Output> {
    // Validation
    if data.id.is_empty() {
        return Err(anyhow!("ID is required"));
    }
    if data.value < 0 {
        return Err(anyhow!("Value must be positive"));
    }
    // Processing
    let result = calculate(data);
    Ok(result)
}

fn process_data_b(data: &Data) -> Result<Output> {
    // Same validation code duplicated
    if data.id.is_empty() {
        return Err(anyhow!("ID is required"));
    }
    if data.value < 0 {
        return Err(anyhow!("Value must be positive"));
    }
    // Processing
    let result = calculate(data);
    Ok(result)
}
rust
// AFTER - Applied DRY principle
fn validate_data(data: &Data) -> Result<()> {
    if data.id.is_empty() {
        return Err(anyhow!("ID is required"));
    }
    if data.value < 0 {
        return Err(anyhow!("Value must be positive"));
    }
    Ok(())
}

fn process_data_a(data: &Data) -> Result<Output> {
    validate_data(data)?;
    let result = calculate(data);
    Ok(result)
}

fn process_data_b(data: &Data) -> Result<Output> {
    validate_data(data)?;
    let result = calculate(data);
    Ok(result)
}

Example 2: Single Responsibility Principle

示例2:单一职责原则

rust
// BEFORE - Single function doing too much
pub fn handle_user_request(data: UserData) -> Result<UserResult> {
    // Validate
    validate_user(&data)?;
    // Store in database
    db::save_user(&data)?;
    // Send email
    email::send_welcome(&data.email)?;
    // Calculate recommendations
    let recs = calculate_recommendations(&data)?;
    Ok(UserResult {
        saved: true,
        recommendations: recs,
    })
}
rust
// AFTER - Split responsibilities
pub struct UserHandler {
    db: Arc<Database>,
    email: Arc<EmailService>,
    recommender: Arc<RecommenderService>,
}

impl UserHandler {
    pub async fn handle_user_request(&self, data: UserData) -> Result<UserResult> {
        // Each function has single responsibility
        self.validate_user(&data)?;
        self.save_user(&data).await?;
        self.send_welcome_email(&data.email).await?;
        let recs = self.get_recommendations(&data).await?;

        Ok(UserResult {
            saved: true,
            recommendations: recs,
        })
    }

    fn validate_user(&self, data: &UserData) -> Result<()> {
        // Validation logic
        Ok(())
    }

    async fn save_user(&self, data: &UserData) -> Result<()> {
        self.db.save_user(data).await
    }

    async fn send_welcome_email(&self, email: &str) -> Result<()> {
        self.email.send_welcome(email).await
    }

    async fn get_recommendations(&self, data: &UserData) -> Result<Vec<Recommendation>> {
        self.recommender.calculate(data).await
    }
}
rust
// BEFORE - Single function doing too much
pub fn handle_user_request(data: UserData) -> Result<UserResult> {
    // Validate
    validate_user(&data)?;
    // Store in database
    db::save_user(&data)?;
    // Send email
    email::send_welcome(&data.email)?;
    // Calculate recommendations
    let recs = calculate_recommendations(&data)?;
    Ok(UserResult {
        saved: true,
        recommendations: recs,
    })
}
rust
// AFTER - Split responsibilities
pub struct UserHandler {
    db: Arc<Database>,
    email: Arc<EmailService>,
    recommender: Arc<RecommenderService>,
}

impl UserHandler {
    pub async fn handle_user_request(&self, data: UserData) -> Result<UserResult> {
        // Each function has single responsibility
        self.validate_user(&data)?;
        self.save_user(&data).await?;
        self.send_welcome_email(&data.email).await?;
        let recs = self.get_recommendations(&data).await?;

        Ok(UserResult {
            saved: true,
            recommendations: recs,
        })
    }

    fn validate_user(&self, data: &UserData) -> Result<()> {
        // Validation logic
        Ok(())
    }

    async fn save_user(&self, data: &UserData) -> Result<()> {
        self.db.save_user(data).await
    }

    async fn send_welcome_email(&self, email: &str) -> Result<()> {
        self.email.send_welcome(email).await
    }

    async fn get_recommendations(&self, data: &UserData) -> Result<Vec<Recommendation>> {
        self.recommender.calculate(data).await
    }
}

Integration with Skills

与其他技能的集成

Complements:
  • rust-code-quality: For Rust-specific quality checks
  • code-reviewer: For comprehensive code review workflows
  • test-runner: For testing refactored code
Invokes:
  • quality-unit-testing: For testing best practices
互补技能:
  • rust-code-quality:用于Rust特有的质量检查
  • code-reviewer:用于全面的代码审查工作流
  • test-runner:用于测试重构后的代码
调用技能:
  • quality-unit-testing:用于测试最佳实践

Tools and Commands

工具与命令

Static Analysis

静态分析

bash
undefined
bash
undefined

Clippy - Rust linter

Clippy - Rust linter

./scripts/code-quality.sh clippy --workspace
./scripts/code-quality.sh clippy --workspace

Check for specific issues

Check for specific issues

cargo clippy -- -W clippy::too_many_arguments cargo clippy -- -W clippy::unwrap_used
undefined
cargo clippy -- -W clippy::too_many_arguments cargo clippy -- -W clippy::unwrap_used
undefined

Complexity Analysis

复杂度分析

bash
undefined
bash
undefined

Install complexity tool

Install complexity tool

cargo install cargo-complexity
cargo install cargo-complexity

Analyze complexity

Analyze complexity

cargo complexity
undefined
cargo complexity
undefined

Duplication Detection

重复代码检测

bash
undefined
bash
undefined

Use tools like jscpd, SonarQube, or custom scripts

Use tools like jscpd, SonarQube, or custom scripts

Find duplicated code blocks

Find duplicated code blocks

undefined
undefined

Quality Gates

质量门禁

Ensure code passes these quality gates:
  • Formatting: 100% rustfmt compliant
  • Linting: Zero clippy warnings
  • Complexity: Cyclomatic complexity < 10 per function
  • Test Coverage: > 90% line coverage
  • Duplication: < 5% duplicate code
  • Documentation: All public APIs documented
确保代码通过以下质量门禁:
  • 格式化:100%符合rustfmt规范
  • 代码检查:零clippy警告
  • 复杂度:每个函数的圈复杂度<10
  • 测试覆盖率:行覆盖率>90%
  • 重复代码:重复代码占比<5%
  • 文档:所有公共API都有文档

Continuous Improvement

持续改进

Weekly Reviews

每周审查

  • Review code quality metrics
  • Identify trends and issues
  • Update coding standards if needed
  • Refactor technical debt
  • 审查代码质量指标
  • 识别趋势与问题
  • 必要时更新编码标准
  • 重构技术债务

Retrospectives

回顾会议

  • Analyze what worked well
  • Identify common issues
  • Improve guidelines
  • Share learnings with team
  • 分析有效的实践
  • 识别常见问题
  • 改进指导方针
  • 与团队分享经验

Summary

总结

Clean code development produces software that is:
  • Readable: Easy to understand by others
  • Maintainable: Easy to modify and extend
  • Testable: Easy to write tests for
  • Efficient: Minimal technical debt
  • Reliable: Fewer bugs and issues
Apply these principles systematically to write code that stands the test of time.
整洁代码开发产出的软件具备以下特性:
  • 可读性:易于他人理解
  • 可维护性:易于修改与扩展
  • 可测试性:易于编写测试
  • 高效性:技术债务最少
  • 可靠性:更少的bug与问题
系统性地应用这些原则,编写经得起时间考验的代码。