architecture-validate-srp

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Validate Single Responsibility Principle (SRP)

验证单一职责原则(SRP)

Automated detection of SRP violations using actor-driven analysis, metrics, and AST patterns.
通过参与者驱动分析、指标及AST模式自动检测SRP违规情况。

Purpose

用途

Detect Single Responsibility Principle violations using multi-dimensional analysis including naming patterns, class metrics, method complexity, cohesion measurements, and project-specific architectural patterns. Provides actionable fix guidance with confidence scoring and refactoring estimates.
通过多维度分析检测单一职责原则违规情况,分析维度包括命名模式、类指标、方法复杂度、内聚性度量及项目特定架构模式。同时提供带有置信度评分和重构工作量估算的可执行修复指导。

Table of Contents

目录

Core Sections

核心章节

Detailed Sections

详细章节

Quick Start

快速开始

User asks: "Check if this class is doing too much" or "Validate SRP compliance"
What happens:
  1. Scans code for SRP violations (naming, size, complexity, dependencies)
  2. Calculates cohesion metrics (TCC, ATFD, WMC)
  3. Detects project-specific anti-patterns
  4. Reports violations with specific refactoring guidance
  5. Estimates refactoring time and effort
Result: ✅ SRP compliant OR ❌ Violations with actionable fixes
用户询问: "检查这个类是否职责过多" 或 "验证SRP合规性"
执行流程:
  1. 扫描代码中的SRP违规情况(命名、大小、复杂度、依赖)
  2. 计算内聚性指标(TCC、ATFD、WMC)
  3. 检测项目特定的反模式
  4. 报告违规情况并提供具体的重构指导
  5. 估算重构时间和工作量
结果: ✅ 符合SRP要求 或 ❌ 存在违规并提供可执行修复方案

When to Use This Skill

何时使用本技能

Invoke this skill when:
  • User asks: "check SRP", "single responsibility", "is this doing too much"
  • User asks: "god class", "too many dependencies", "method too long"
  • Before commit (as part of
    code-review
    skill)
  • During refactoring or architectural review
  • As quality gate (via
    run-quality-gates
    skill)
  • When class/method feels complex but can't articulate why
Integration triggers:
  • code-review
    skill Step 2: Architectural Review (SRP sub-check)
  • validate-architecture
    skill: SRP at layer level
  • run-quality-gates
    skill: Optional SRP quality gate
  • multi-file-refactor
    skill: SRP-driven refactoring coordination
在以下场景调用本技能:
  • 用户询问:"检查SRP"、"单一职责"、"这个类是否职责过多"
  • 用户询问:"上帝类"、"依赖过多"、"方法过长"
  • 提交代码前(作为
    code-review
    技能的一部分)
  • 重构或架构评审过程中
  • 作为质量门禁(通过
    run-quality-gates
    技能)
  • 感觉类/方法复杂但无法明确原因时
集成触发点:
  • code-review
    技能第2步:架构评审(SRP子检查)
  • validate-architecture
    技能:层级级别的SRP检查
  • run-quality-gates
    技能:可选的SRP质量门禁
  • multi-file-refactor
    技能:基于SRP的重构协调

What This Skill Does

本技能的功能

SRP Definition (Actor-Driven)

SRP定义(参与者驱动)

Robert C. Martin: "A module should be responsible to one, and only one, actor."
  • Actor: A group of users or stakeholders who would request changes
  • NOT "do one thing" (task-driven) - a class can have multiple methods
  • IS "have one reason to change" (actor-driven)
Example: See examples/violation-naming-patterns.py for violation and correct implementation showing Employee class serving 3 actors (Accounting, HR, DBA) and the correct split into PayCalculator, HourReporter, and EmployeeRepository.
罗伯特·C·马丁: "一个模块应该只对一个,且仅对一个参与者负责。"
  • 参与者:会请求变更的一组用户或利益相关者
  • 不是 "只做一件事"(任务驱动)——一个类可以有多个方法
  • 而是 "只有一个变更的理由"(参与者驱动)
示例: 参见examples/violation-naming-patterns.py中的违规案例及正确实现,展示了为3个参与者(会计、HR、数据库管理员)服务的Employee类,以及拆分后的PayCalculator、HourReporter和EmployeeRepository类。

Detection Methods (Multi-Dimensional)

检测方法(多维度)

This skill uses 4 validation levels:
  1. Level 1 (Fast, 5s): Naming patterns via AST-grep
    • Methods with "and" in name → 40% confidence violation
    • Quick scan of entire codebase
  2. Level 2 (Fast, 10s): Size metrics via AST analysis
    • Class >300 lines → Review needed
    • Method >50 lines → 60% confidence violation
    • 15 methods per class → Review needed
  3. Level 3 (Moderate, 30s): Cohesion metrics
    • God Class: ATFD >5 AND WMC >47 AND TCC <0.33 → 80% confidence
    • Constructor >4 params (warning), >8 params (critical) → 75% confidence
  4. Level 4 (Manual, 5min): Actor analysis (guided questions)
    • "How many actors would request changes to this class?"
    • "Can you split by actor responsibility?"
Default mode: Level 2 (Fast + Size metrics) - balance speed and accuracy
本技能采用4级验证机制
  1. 级别1(快速,5秒):通过AST-grep检查命名模式
    • 方法名包含"and" → 40%置信度的违规
    • 快速扫描整个代码库
  2. 级别2(快速,10秒):通过AST分析检查大小指标
    • 类代码超过300行 → 需要评审
    • 方法代码超过50行 → 60%置信度的违规
    • 类包含超过15个方法 → 需要评审
  3. 级别3(中等,30秒):内聚性指标检查
    • 上帝类:ATFD >5 且 WMC >47 且 TCC <0.33 → 80%置信度
    • 构造函数参数超过4个(警告),超过8个(严重)→75%置信度
  4. 级别4(手动,5分钟):参与者分析(引导式问题)
    • "有多少参与者会请求修改这个类?"
    • "你能否按参与者对方法进行分组?"
默认模式: 级别2(快速+大小指标)——平衡速度和准确性

Validation Levels

验证级别

LevelSpeedChecksUse When
fast
5sNaming patterns onlyQuick pre-commit scan
thorough
30sNaming + Size + MetricsNormal workflow (default)
full
5minAll checks + Actor analysisDeep refactoring review
级别速度检查内容使用场景
fast
5秒仅命名模式提交前快速扫描
thorough
30秒命名+大小+指标常规工作流(默认)
full
5分钟所有检查+参与者分析深度重构评审

Instructions

操作说明

Step 1: Determine Validation Level

步骤1:确定验证级别

bash
undefined
bash
undefined

User request → Validation level

用户请求 → 验证级别

"quick check" → fast "review this class" → thorough (default) "plan refactoring" → full
undefined
"快速检查" → fast "评审这个类" → thorough(默认) "规划重构" → full
undefined

Step 2: Detect Naming Violations (All Levels)

步骤2:检测命名违规(所有级别)

Pattern 1: Methods with "and" in name (40% confidence)
Use the validation script to detect naming violations:
Using validation script:
bash
./scripts/validate-srp.sh <path> --level=fast
Or manually with MCP tools:
bash
mcp__ast-grep__find_code(
    pattern="def $NAME_and_$REST",
    project_folder="/path/to/project",
    language="python"
)
Example violations and fixes: See examples/violation-naming-patterns.py showing validate_and_save_user() violation and the correct split into validate_user() and save_user().
模式1:方法名包含"and"(40%置信度)
使用验证脚本检测命名违规:
使用验证脚本:
bash
./scripts/validate-srp.sh <path> --level=fast
或使用MCP工具手动检测:
bash
mcp__ast-grep__find_code(
    pattern="def $NAME_and_$REST",
    project_folder="/path/to/project",
    language="python"
)
违规案例及修复示例: 参见examples/violation-naming-patterns.py中的validate_and_save_user()违规案例,以及拆分后的validate_user()和save_user()正确实现。

Step 3: Analyze Size Metrics (Thorough+)

步骤3:分析大小指标(全面级别及以上)

Pattern 2: Class size (300+ lines → review)
Use the validation script for size analysis:
bash
./scripts/validate-srp.sh <path> --level=thorough
Or use God Class detection script:
bash
./scripts/check-god-class.sh <file.py>
Thresholds:
  • Class: >300 lines = warning, >500 lines = critical
  • Method: >50 lines = warning, >100 lines = critical
  • Methods per class: >15 = warning, >25 = critical
模式2:类大小(300行以上 → 需要评审)
使用验证脚本进行大小分析:
bash
./scripts/validate-srp.sh <path> --level=thorough
或使用上帝类检测脚本:
bash
./scripts/check-god-class.sh <file.py>
阈值:
  • 类:超过300行 = 警告,超过500行 = 严重
  • 方法:超过50行 = 警告,超过100行 = 严重
  • 类的方法数量:超过15个 = 警告,超过25个 = 严重

Step 4: Calculate Cohesion Metrics (Thorough+)

步骤4:计算内聚性指标(全面级别及以上)

God Class Detection (80% confidence):
  • ATFD (Access to Foreign Data): >5 = excessive coupling
  • WMC (Weighted Methods per Class): >47 = too complex
  • TCC (Tight Class Cohesion): <0.33 = low cohesion
Formula:
ATFD >5 AND WMC >47 AND TCC <0.33 → God Class
Calculate metrics using radon:
bash
undefined
上帝类检测(80%置信度):
  • ATFD(访问外部数据):>5 = 过度耦合
  • WMC(类的加权方法数):>47 = 过于复杂
  • TCC(紧密类内聚性):<0.33 = 内聚性低
公式:
ATFD >5 且 WMC >47 且 TCC <0.33 → 上帝类
使用radon计算指标:
bash
undefined

If radon available

如果已安装radon

uv run radon cc src/ -a -nb # Cyclomatic complexity (WMC proxy) uv run radon raw src/ # Raw metrics

**See:** [references/srp-principles.md](./references/srp-principles.md) for detailed metric calculations and formulas.
uv run radon cc src/ -a -nb # 圈复杂度(WMC替代指标) uv run radon raw src/ # 原始指标

**参考:** [references/srp-principles.md](./references/srp-principles.md)中的详细指标计算方法和公式。

Step 5: Detect Constructor Dependencies (Thorough+)

步骤5:检测构造函数依赖(全面级别及以上)

Pattern 4: Constructor parameters (>4 warning, >8 critical)
Use the God Class detection script:
bash
./scripts/check-god-class.sh <file.py>
Thresholds (75% confidence):
  • 1-4 params: ✅ Good
  • 5-8 params: ⚠️ Warning (consider parameter object)
  • 9+ params: ❌ Critical (God Class indicator)
Example violations and fixes: See examples/violation-god-class.py showing UserService with 9 constructor parameters and the correct split into UserAuthService, UserNotificationService, and UserAnalytics.
模式4:构造函数参数(超过4个警告,超过8个严重)
使用上帝类检测脚本:
bash
./scripts/check-god-class.sh <file.py>
阈值(75%置信度):
  • 1-4个参数:✅ 良好
  • 5-8个参数:⚠️ 警告(考虑使用参数对象)
  • 9个及以上参数:❌ 严重(上帝类标志)
违规案例及修复示例: 参见examples/violation-god-class.py中的UserService类(包含9个构造函数参数),以及拆分后的UserAuthService、UserNotificationService和UserAnalytics类。

Step 6: Detect Project-Specific Patterns

步骤6:检测项目特定模式

Read CLAUDE.md for project anti-patterns:
Check for project-specific SRP violations using grep:
bash
undefined
阅读CLAUDE.md了解项目反模式:
使用grep检查项目特定的SRP违规情况:
bash
undefined

Pattern 1: Optional config parameters (project anti-pattern)

模式1:可选配置参数(项目反模式)

grep -rn "config.*Optional|config.None.=" src/
grep -rn "config.*Optional|config.None.=" src/

Pattern 2: Domain entities doing I/O (layer violation)

模式2:领域实体执行I/O(层级违规)

grep -r "import.*requests|import.*database" domain/
grep -r "import.*requests|import.*database" domain/

Pattern 3: Application services with business logic

模式3:应用服务包含业务逻辑

grep -r "def calculate|def compute" application/services/
grep -r "def calculate|def compute" application/services/

Pattern 4: Repositories with orchestration

模式4:仓库包含编排逻辑

grep -A 10 "class.*Repository" infrastructure/repositories/

**Common project-specific violations:**
- Domain entities importing infrastructure
- Application services implementing business logic (should orchestrate only)
- Repositories containing orchestration (should be data access only)
- Optional config parameters (violates fail-fast)

**See:** [references/srp-principles.md](./references/srp-principles.md) for actor identification guidance.
grep -A 10 "class.*Repository" infrastructure/repositories/

**常见项目特定违规:**
- 领域实体导入基础设施代码
- 应用服务实现业务逻辑(应仅负责编排)
- 仓库包含编排逻辑(应仅负责数据访问)
- 可选配置参数(违反快速失败原则)

**参考:** [references/srp-principles.md](./references/srp-principles.md)中的参与者识别指南。

Step 7: Actor Analysis (Full Mode Only)

步骤7:参与者分析(仅完整模式)

Guided questions for user:
  1. "List all actors who would request changes to this class:"
    • Example: "HR department, Accounting team, DBA"
  2. "Can you group methods by actor?"
    • Example:
      calculate_pay()
      → Accounting,
      report_hours()
      → HR
  3. "How would you name classes split by actor?"
    • Example:
      PayCalculator
      ,
      HourReporter
      ,
      EmployeeRepository
Actor count → Violation confidence:
  • 1 actor: ✅ SRP compliant
  • 2 actors: ⚠️ Warning (consider split)
  • 3+ actors: ❌ Violation (must split)
向用户提出的引导式问题:
  1. "列出所有会请求修改这个类的参与者:"
    • 示例:"HR部门、会计团队、数据库管理员"
  2. "你能否按参与者对方法进行分组?"
    • 示例:
      calculate_pay()
      → 会计,
      report_hours()
      → HR
  3. "你会如何为按参与者拆分后的类命名?"
    • 示例:
      PayCalculator
      HourReporter
      EmployeeRepository
参与者数量 → 违规置信度:
  • 1个参与者:✅ 符合SRP
  • 2个参与者:⚠️ 警告(考虑拆分)
  • 3个及以上参与者:❌ 违规(必须拆分)

Step 8: Generate Report

步骤8:生成报告

Report structure:
SRP Validation Report
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

✅ Passed: X/Y classes (Z%)

❌ Violations Found: N

[CRITICAL] God Class: ClassName (path/file.py:line)
  - Lines: X (threshold: 300)
  - Methods: Y (threshold: 15)
  - Constructor params: Z (threshold: 4)
  - ATFD: A, WMC: B, TCC: C
  - Actors detected: N (actor1, actor2, actor3)
  - Fix: Split into Class1 (actor1), Class2 (actor2), Class3 (actor3)
  - Estimated refactoring: A-B hours

[WARNING] Method Name Violation: method_and_other (path/file.py:line)
  - Method name contains 'and'
  - Confidence: 40%
  - Fix: Split into method() and other()
  - Estimated refactoring: 15-30 minutes

[WARNING] Long Method: process_request (path/file.py:line)
  - Lines: X (threshold: 50)
  - Cyclomatic complexity: Y (threshold: 10)
  - Confidence: 60%
  - Fix: Extract 2-3 smaller methods
  - Estimated refactoring: 30-60 minutes

Summary:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
- X critical violations (must fix)
- Y warnings (should fix)
- Total estimated refactoring time: A-B hours
- Top priority: ClassName (god class)
报告结构:
SRP验证报告
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

✅ 通过:X/Y个类(Z%)

❌ 发现违规:N个

[严重] 上帝类:ClassName (path/file.py:line)
  - 代码行数:X(阈值:300)
  - 方法数量:Y(阈值:15)
  - 构造函数参数:Z(阈值:4)
  - ATFD: A, WMC: B, TCC: C
  - 检测到的参与者:N个(参与者1、参与者2、参与者3)
  - 修复方案:拆分为Class1(参与者1)、Class2(参与者2)、Class3(参与者3)
  - 估算重构时间:A-B小时

[警告] 方法名违规:method_and_other (path/file.py:line)
  - 方法名包含'and'
  - 置信度:40%
  - 修复方案:拆分为method()和other()
  - 估算重构时间:15-30分钟

[警告] 方法过长:process_request (path/file.py:line)
  - 代码行数:X(阈值:50)
  - 圈复杂度:Y(阈值:10)
  - 置信度:60%
  - 修复方案:提取2-3个更小的方法
  - 估算重构时间:30-60分钟

摘要:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
- X个严重违规(必须修复)
- Y个警告(建议修复)
- 总估算重构时间:A-B小时
- 最高优先级:ClassName(上帝类)

Usage Examples

使用示例

Example 1: Quick Pre-Commit Check

示例1:提交前快速检查

bash
undefined
bash
undefined

User: "Quick SRP check before commit"

用户:"提交前快速检查SRP"

Skill runs level: fast (5s)

技能运行级别:fast(5秒)

→ Scans for method names with "and" → Reports 2 violations
Output: ⚠️ 2 SRP warnings found:
  1. validate_and_save_user (src/services/user.py:45)
    • Method name contains 'and'
    • Fix: Split into validate_user() and save_user()
  2. fetch_and_transform_data (src/utils/data.py:78)
    • Method name contains 'and'
    • Fix: Split into fetch_data() and transform_data()
Run with --thorough for complete analysis.
undefined
→ 扫描方法名包含"and"的情况 → 报告2个违规
输出: ⚠️ 发现2个SRP警告:
  1. validate_and_save_user (src/services/user.py:45)
    • 方法名包含'and'
    • 修复方案:拆分为validate_user()和save_user()
  2. fetch_and_transform_data (src/utils/data.py:78)
    • 方法名包含'and'
    • 修复方案:拆分为fetch_data()和transform_data()
使用--thorough参数进行完整分析。
undefined

Example 2: Class Review (Default)

示例2:类评审(默认)

bash
undefined
bash
undefined

User: "Review UserService for SRP compliance"

用户:"评审UserService的SRP合规性"

Skill runs level: thorough (30s)

技能运行级别:thorough(30秒)

→ Naming patterns → Size metrics → Cohesion metrics → Constructor analysis
Output: ❌ UserService violates SRP (src/application/services/user_service.py:12)
Violations:
  • Lines: 487 (threshold: 300) ❌
  • Methods: 23 (threshold: 15) ⚠️
  • Constructor params: 9 (threshold: 4) ❌
  • ATFD: 12 (threshold: 5) ❌
  • WMC: 89 (threshold: 47) ❌
  • TCC: 0.21 (threshold: 0.33) ❌
Detected actors (3):
  1. Authentication (login, logout, verify_token)
  2. Profile Management (update_profile, get_profile, delete_account)
  3. Notifications (send_welcome_email, send_reset_email)
Recommended split:
  • UserAuthService: authentication methods
  • UserProfileService: profile management
  • UserNotificationService: notification methods
Estimated refactoring: 4-6 hours
undefined
→ 命名模式检查 → 大小指标检查 → 内聚性指标检查 → 构造函数分析
输出: ❌ UserService违反SRP规范 (src/application/services/user_service.py:12)
违规情况:
  • 代码行数:487(阈值:300) ❌
  • 方法数量:23(阈值:15) ⚠️
  • 构造函数参数:9(阈值:4) ❌
  • ATFD: 12(阈值:5) ❌
  • WMC: 89(阈值:47) ❌
  • TCC: 0.21(阈值:0.33) ❌
检测到的参与者(3个):
  1. 认证(login、logout、verify_token)
  2. 资料管理(update_profile、get_profile、delete_account)
  3. 通知(send_welcome_email、send_reset_email)
建议拆分:
  • UserAuthService:认证相关方法
  • UserProfileService:资料管理相关方法
  • UserNotificationService:通知相关方法
估算重构时间:4-6小时
undefined

Example 3: Deep Refactoring Analysis

示例3:深度重构分析

bash
undefined
bash
undefined

User: "Plan refactoring for PaymentProcessor - full SRP analysis"

用户:"为PaymentProcessor规划重构 - 完整SRP分析"

Skill runs level: full (5 min with user interaction)

技能运行级别:full(5分钟,含用户交互)

→ All automated checks → Actor analysis questions → Refactoring plan
Questions asked:
  1. "List actors who request changes to PaymentProcessor" User: "Finance team, Fraud detection, Customer support, Compliance"
  2. "Group methods by actor" User provides grouping...
Output: ❌ PaymentProcessor is a God Class (4 actors detected)
Actor breakdown:
  1. Finance (3 methods): process_payment, refund_payment, calculate_fees
  2. Fraud Detection (2 methods): check_fraud_score, block_suspicious
  3. Customer Support (2 methods): get_transaction_history, dispute_charge
  4. Compliance (2 methods): log_transaction, generate_audit_report
Refactoring plan: Phase 1 (2 hours): Extract PaymentProcessor (Finance actor) Phase 2 (1.5 hours): Extract FraudDetectionService Phase 3 (1.5 hours): Extract TransactionHistoryService (Support) Phase 4 (1 hour): Extract ComplianceReporter Phase 5 (1 hour): Integration tests and validation
Total estimated time: 7 hours Recommended approach: Incremental (1 phase per day)
undefined
→ 所有自动化检查 → 参与者分析问题 → 重构方案
提出的问题:
  1. "列出会请求修改PaymentProcessor的参与者" 用户:"财务团队、欺诈检测、客户支持、合规部门"
  2. "按参与者对方法进行分组" 用户提供分组...
输出: ❌ PaymentProcessor是上帝类(检测到4个参与者)
参与者细分:
  1. 财务(3个方法):process_payment、refund_payment、calculate_fees
  2. 欺诈检测(2个方法):check_fraud_score、block_suspicious
  3. 客户支持(2个方法):get_transaction_history、dispute_charge
  4. 合规(2个方法):log_transaction、generate_audit_report
重构方案: 阶段1(2小时):提取PaymentProcessor(财务参与者) 阶段2(1.5小时):提取FraudDetectionService 阶段3(1.5小时):提取TransactionHistoryService(客户支持) 阶段4(1小时):提取ComplianceReporter 阶段5(1小时):集成测试和验证
总估算时间:7小时 推荐方法:增量式重构(每天完成一个阶段)
undefined

Integration with Other Skills

与其他技能的集成

With code-review

与code-review集成

The
code-review
skill invokes SRP validation in Step 2 (Architectural Review) as a sub-check. When SRP violations are detected, they are reported as warnings in the overall code review report.
Integration point: Automatic invocation during code review workflow with
level="fast"
for speed.
code-review
技能在第2步(架构评审)中调用SRP验证作为子检查。当检测到SRP违规时,会在整体代码评审报告中作为警告列出。
集成点: 代码评审工作流中自动调用,使用
level="fast"
以保证速度。

With validate-architecture

与validate-architecture集成

The
validate-architecture
skill checks SRP compliance at the layer level, while this skill checks at the class/method level. Domain layers should have high cohesion (TCC > 0.5), and this skill can detect low cohesion violations.
Integration point: Cross-layer validation to ensure architectural boundaries maintain SRP.
validate-architecture
技能在层级级别检查SRP合规性,而本技能在类/方法级别检查。领域层应具有高内聚性(TCC > 0.5),本技能可检测内聚性低的违规情况。
集成点: 跨层级验证,确保架构边界符合SRP规范。

With run-quality-gates

与run-quality-gates集成

SRP validation can be added as an optional quality gate in
.claude/quality-gates.json
:
json
{
  "optional_gates": ["srp_validation"],
  "srp_threshold": "warning"
}
Set threshold to
"critical"
to block commits on violations.
可在
.claude/quality-gates.json
中添加SRP验证作为可选质量门禁:
json
{
  "optional_gates": ["srp_validation"],
  "srp_threshold": "warning"
}
将阈值设置为
"critical"
可在出现违规时阻止代码提交。

With multi-file-refactor

与multi-file-refactor集成

When refactoring God Classes that span multiple files, use
multi-file-refactor
skill to coordinate changes. This skill identifies God Classes and provides refactoring guidance;
multi-file-refactor
executes the split.
当重构跨多个文件的上帝类时,使用
multi-file-refactor
技能协调变更。本技能识别上帝类并提供重构指导;
multi-file-refactor
执行拆分操作。

Parameters

参数

ParameterTypeDefaultDescription
path
string
src/
File or directory to validate
level
enum
thorough
Validation depth:
fast
,
thorough
,
full
output_format
enum
text
Output format:
text
,
json
threshold
enum
warning
Report threshold:
warning
,
critical
include_metrics
bool
true
Include cohesion metrics in report
Usage:
bash
undefined
参数类型默认值描述
path
string
src/
要验证的文件或目录
level
enum
thorough
验证深度:
fast
thorough
full
output_format
enum
text
输出格式:
text
json
threshold
enum
warning
报告阈值:
warning
critical
include_metrics
bool
true
报告中包含内聚性指标
使用方式:
bash
undefined

Default (thorough mode on src/)

默认(对src/执行thorough模式)

Skill(command: "validate-srp")
Skill(command: "validate-srp")

Custom path and level

自定义路径和级别

Skill(command: "validate-srp --path=src/application --level=full")
Skill(command: "validate-srp --path=src/application --level=full")

JSON output for tooling integration

JSON输出用于工具集成

Skill(command: "validate-srp --output_format=json")
undefined
Skill(command: "validate-srp --output_format=json")
undefined

Output Format

输出格式

Text Output (Default)

文本输出(默认)

See Step 8 in Instructions for complete example.
参见操作说明中的步骤8完整示例。

JSON Output

JSON输出

json
{
  "summary": {
    "total_classes": 45,
    "violations": 7,
    "warnings": 12,
    "passed": 26,
    "compliance_rate": 0.58
  },
  "violations": [
    {
      "severity": "critical",
      "type": "god_class",
      "class": "UserService",
      "file": "src/application/services/user_service.py",
      "line": 12,
      "metrics": {
        "lines": 487,
        "methods": 23,
        "constructor_params": 9,
        "atfd": 12,
        "wmc": 89,
        "tcc": 0.21
      },
      "actors": ["Authentication", "Profile", "Notifications"],
      "confidence": 0.80,
      "fix": "Split into UserAuthService, UserProfileService, UserNotificationService",
      "estimated_hours": 5.0
    }
  ],
  "warnings": [
    {
      "severity": "warning",
      "type": "method_naming",
      "method": "validate_and_save_user",
      "file": "src/services/user.py",
      "line": 45,
      "confidence": 0.40,
      "fix": "Split into validate_user() and save_user()",
      "estimated_minutes": 20
    }
  ]
}
json
{
  "summary": {
    "total_classes": 45,
    "violations": 7,
    "warnings": 12,
    "passed": 26,
    "compliance_rate": 0.58
  },
  "violations": [
    {
      "severity": "critical",
      "type": "god_class",
      "class": "UserService",
      "file": "src/application/services/user_service.py",
      "line": 12,
      "metrics": {
        "lines": 487,
        "methods": 23,
        "constructor_params": 9,
        "atfd": 12,
        "wmc": 89,
        "tcc": 0.21
      },
      "actors": ["Authentication", "Profile", "Notifications"],
      "confidence": 0.80,
      "fix": "Split into UserAuthService, UserProfileService, UserNotificationService",
      "estimated_hours": 5.0
    }
  ],
  "warnings": [
    {
      "severity": "warning",
      "type": "method_naming",
      "method": "validate_and_save_user",
      "file": "src/services/user.py",
      "line": 45,
      "confidence": 0.40,
      "fix": "Split into validate_user() and save_user()",
      "estimated_minutes": 20
    }
  ]
}

Supporting Files

支持文件

References

参考资料

  • references/srp-principles.md - Core SRP concepts, actor-driven definition, real-world examples, cohesion metrics formulas
  • references/srp-principles.md - 核心SRP概念、参与者驱动定义、真实场景示例、内聚性指标公式

Examples

示例

  • examples/examples.md - Overview of all examples with expected results
  • examples/violation-naming-patterns.py - Methods with "and" in name, multiple actors
  • examples/violation-god-class.py - Constructor with too many parameters
  • examples/correct-single-actor.py - Proper SRP implementation with single actor
  • examples/examples.md - 所有示例的概述及预期结果
  • examples/violation-naming-patterns.py - 方法名包含"and"的违规案例,涉及多个参与者
  • examples/violation-god-class.py - 构造函数参数过多的违规案例
  • examples/correct-single-actor.py - 符合SRP规范的单一参与者实现

Scripts

脚本

  • scripts/validate-srp.sh - Main validation script with 3 levels (fast/thorough/full)
  • scripts/check-god-class.sh - God Class detection for individual files
  • scripts/validate-srp.sh - 主验证脚本,支持3个级别(fast/thorough/full)
  • scripts/check-god-class.sh - 针对单个文件的上帝类检测脚本

Success Metrics

成功指标

MetricTargetBenefit
Detection accuracy>85%Minimal false positives
God class detection100%Catch all critical violations
False positive rate<15%High signal-to-noise ratio
Execution time<30sFast enough for workflow
Actionability100%Every violation has specific fix
Refactoring estimate accuracy±30%Reliable planning
指标目标收益
检测准确率>85%最小化误报
上帝类检测率100%捕获所有严重违规
误报率<15%高信噪比
执行时间<30秒足够快以融入工作流
可执行性100%每个违规都有具体修复方案
重构估算准确率±30%可靠的规划依据

Utility Scripts

实用脚本

validate-srp.sh

validate-srp.sh

Main validation script with multi-level analysis:
bash
undefined
支持多级别分析的主验证脚本:
bash
undefined

Fast check (naming patterns only - 5 seconds)

快速检查(仅命名模式 - 5秒)

./scripts/validate-srp.sh src/ --level=fast
./scripts/validate-srp.sh src/ --level=fast

Thorough check (naming + size + constructors - 30 seconds)

全面检查(命名+大小+构造函数 - 30秒)

./scripts/validate-srp.sh src/ --level=thorough
./scripts/validate-srp.sh src/ --level=thorough

Full analysis (with actor questions - 5 minutes)

完整分析(含参与者问题 - 5分钟)

./scripts/validate-srp.sh src/ --level=full
./scripts/validate-srp.sh src/ --level=full

JSON output for CI/CD integration

JSON输出用于CI/CD集成

./scripts/validate-srp.sh src/ --output-format=json
undefined
./scripts/validate-srp.sh src/ --output-format=json
undefined

check-god-class.sh

check-god-class.sh

Focused God Class detection for single files:
bash
undefined
针对单个文件的聚焦式上帝类检测:
bash
undefined

Check specific file

检查特定文件

./scripts/check-god-class.sh src/services/user_service.py
./scripts/check-god-class.sh src/services/user_service.py

Returns:

返回:

- Constructor parameter count

- 构造函数参数数量

- Method count

- 方法数量

- File size

- 文件大小

- God Class recommendation

- 上帝类判定建议

undefined
undefined

Requirements

要求

Minimum:
  • Python 3.10+ (for AST analysis)
  • Read, Grep, Bash, Glob tools
  • Source code in supported language (Python/JS/TS)
  • Validation scripts in scripts/ directory
Optional:
  • radon
    for accurate metrics:
    uv pip install radon
  • mcp__ast-grep__*
    tools for precise AST analysis
  • mcp__project-watch-mcp__search_code
    for context
Installation:
bash
undefined
最低要求:
  • Python 3.10+(用于AST分析)
  • Read、Grep、Bash、Glob工具
  • 支持语言的源代码(Python/JS/TS)
  • scripts/目录下的验证脚本
可选要求:
  • radon
    (用于精确指标计算):
    uv pip install radon
  • mcp__ast-grep__*
    工具(用于精确AST分析)
  • mcp__project-watch-mcp__search_code
    (用于上下文分析)
安装步骤:
bash
undefined

Make scripts executable

为脚本添加执行权限

chmod +x scripts/*.sh
chmod +x scripts/*.sh

Optional: Install radon for accurate metrics

可选:安装radon以获取精确指标

uv pip install radon
uv pip install radon

Verify installation

验证安装

uv run radon --version
undefined
uv run radon --version
undefined

Red Flags to Avoid

需要避免的红色警示

Architectural Violations

架构违规

  1. God Classes - ATFD >5, WMC >47, TCC <0.33
  2. Constructor Dependencies - >8 parameters
  3. Method Naming - Methods with "and" in name
  4. File Size - >500 lines per file
  1. 上帝类 - ATFD >5, WMC >47, TCC <0.33
  2. 构造函数依赖过多 - 参数超过8个
  3. 方法命名违规 - 方法名包含"and"
  4. 文件过大 - 单个文件超过500行

Detection Anti-Patterns

检测反模式

  1. Ignoring warnings - Small violations compound into big issues
  2. Not validating fixes - Re-run after refactoring
  3. Skipping actor analysis - Metrics alone miss context
  4. Assuming SRP = "one method" - SRP is actor-driven, not task-driven
  1. 忽略警告 - 小违规会累积成大问题
  2. 不验证修复效果 - 重构后需重新运行检查
  3. 跳过参与者分析 - 仅靠指标会遗漏上下文
  4. 认为SRP = "一个方法" - SRP是参与者驱动,而非任务驱动

Process Mistakes

流程错误

  1. Refactoring without tests - Always have test coverage first
  2. Big bang refactoring - Incremental refactoring safer
  3. Not estimating effort - Plan time for refactoring
  4. Skipping after major changes - Validation most critical after refactoring
  1. 无测试覆盖时重构 - 重构前必须有测试覆盖
  2. 大规模一次性重构 - 增量式重构更安全
  3. 不估算工作量 - 为重构规划时间
  4. 重大变更后不验证 - 重大变更后验证最为关键

Troubleshooting

故障排除

Issue: Too Many False Positives

问题:误报过多

Symptom: Small helper methods flagged as violations
Fix: Adjust thresholds in
.claude/srp-config.json
:
json
{
  "thresholds": {
    "class_lines": 400,
    "method_lines": 75,
    "constructor_params": 6
  }
}
症状: 小型辅助方法被标记为违规
修复:
.claude/srp-config.json
中调整阈值:
json
{
  "thresholds": {
    "class_lines": 400,
    "method_lines": 75,
    "constructor_params": 6
  }
}

Issue: Metrics Not Calculated

问题:指标未计算

Symptom: "Metrics unavailable" in report
Fix: Install radon:
bash
uv pip install radon
Or use simplified heuristics (less accurate but faster).
症状: 报告中显示"Metrics unavailable"
修复: 安装radon:
bash
uv pip install radon
或使用简化启发式方法(准确性较低但速度更快)。

Issue: Can't Identify Actors

问题:无法识别参与者

Symptom: Actor analysis unclear
Fix: Ask targeted questions:
  1. "Who would request changes to this class?"
  2. "Can you group methods by job role?"
  3. "What teams interact with this code?"
症状: 参与者分析不清晰
修复: 提出针对性问题:
  1. "谁会请求修改这个类?"
  2. "你能否按岗位角色对方法进行分组?"
  3. "哪些团队会与这段代码交互?"

Expected Benefits

预期收益

MetricWithout SRP ValidationWith SRP ValidationImprovement
God classes in codebase15-250-295% reduction
Time to understand class20-45 min5-10 min75% faster
Bugs per class8-12 per year1-3 per year85% reduction
Refactoring costHigh (embedded violations)Low (caught early)80% reduction
Test coverage40-60% (hard to test)80-95% (easy to test)50% increase
Code review time30-60 min10-20 min66% faster
指标无SRP验证有SRP验证提升效果
代码库中的上帝类数量15-250-2减少95%
理解类的时间20-45分钟5-10分钟加快75%
每个类每年的bug数量8-121-3减少85%
重构成本高(违规已嵌入)低(早期发现)减少80%
测试覆盖率40-60%(难以测试)80-95%(易于测试)提升50%
代码评审时间30-60分钟10-20分钟加快66%

See Also

相关技能

  • validate-architecture - Layer-level architecture validation
  • code-review - Comprehensive pre-commit review (includes SRP)
  • run-quality-gates - Quality gate orchestration
  • multi-file-refactor - Coordinate SRP-driven refactoring
  • @code-review-expert - Agent for code review guidance
  • @architecture-guardian - Agent for architectural decisions
  • ARCHITECTURE.md - Project architecture documentation

Last Updated: 2025-11-02 Version: 1.0.0
  • validate-architecture - 层级级别的架构验证
  • code-review - 全面的提交前评审(包含SRP检查)
  • run-quality-gates - 质量门禁编排
  • multi-file-refactor - 协调基于SRP的重构
  • @code-review-expert - 代码评审指导Agent
  • @architecture-guardian - 架构决策指导Agent
  • ARCHITECTURE.md - 项目架构文档

最后更新: 2025-11-02 版本: 1.0.0