xiaohongshu
xiaohongshu
architecture-validate-srp
Detect Single Responsibility Principle (SRP) violations using multi-dimensional analysis. Use when reviewing code for "SRP", "single responsibility", "god class", "doing too much", "too many dependencies", before commits, during refactoring, or as quality gate. Analyzes Python, JavaScript, TypeSc...
Full skill instructions
Automated detection of SRP violations using actor-driven analysis, metrics, and AST patterns.
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.
User asks: "Check if this class is doing too much" or "Validate SRP compliance"
What happens:
Result: ✅ SRP compliant OR ❌ Violations with actionable fixes
Invoke this skill when:
code-review skill)run-quality-gates skill)Integration triggers:
code-review skill Step 2: Architectural Review (SRP sub-check)validate-architecture skill: SRP at layer levelrun-quality-gates skill: Optional SRP quality gatemulti-file-refactor skill: SRP-driven refactoring coordinationRobert C. Martin: "A module should be responsible to one, and only one, actor."
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.
This skill uses 4 validation levels:
Level 1 (Fast, 5s): Naming patterns via AST-grep
Level 2 (Fast, 10s): Size metrics via AST analysis
15 methods per class → Review needed
Level 3 (Moderate, 30s): Cohesion metrics
Level 4 (Manual, 5min): Actor analysis (guided questions)
Default mode: Level 2 (Fast + Size metrics) - balance speed and accuracy
| Level | Speed | Checks | Use When |
|---|---|---|---|
fast | 5s | Naming patterns only | Quick pre-commit scan |
thorough | 30s | Naming + Size + Metrics | Normal workflow (default) |
full | 5min | All checks + Actor analysis | Deep refactoring review |
# User request → Validation level
"quick check" → fast
"review this class" → thorough (default)
"plan refactoring" → full
Pattern 1: Methods with "and" in name (40% confidence)
Use the validation script to detect naming violations:
Using validation script:
./scripts/validate-srp.sh <path> --level=fast
Or manually with MCP tools:
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().
Pattern 2: Class size (300+ lines → review)
Use the validation script for size analysis:
./scripts/validate-srp.sh <path> --level=thorough
Or use God Class detection script:
./scripts/check-god-class.sh <file.py>
Thresholds:
God Class Detection (80% confidence):
Formula: ATFD >5 AND WMC >47 AND TCC <0.33 → God Class
Calculate metrics using radon:
# If radon available
uv run radon cc src/ -a -nb # Cyclomatic complexity (WMC proxy)
uv run radon raw src/ # Raw metrics
See: references/srp-principles.md for detailed metric calculations and formulas.
Pattern 4: Constructor parameters (>4 warning, >8 critical)
Use the God Class detection script:
./scripts/check-god-class.sh <file.py>
Thresholds (75% confidence):
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.
Read CLAUDE.md for project anti-patterns:
Check for project-specific SRP violations using grep:
# Pattern 1: Optional config parameters (project anti-pattern)
grep -rn "config.*Optional\|config.*None.*=" src/
# Pattern 2: Domain entities doing I/O (layer violation)
grep -r "import.*requests\|import.*database" domain/
# Pattern 3: Application services with business logic
grep -r "def calculate\|def compute" application/services/
# Pattern 4: Repositories with orchestration
grep -A 10 "class.*Repository" infrastructure/repositories/
Common project-specific violations:
See: references/srp-principles.md for actor identification guidance.
Guided questions for user:
"List all actors who would request changes to this class:"
"Can you group methods by actor?"
calculate_pay() → Accounting, report_hours() → HR"How would you name classes split by actor?"
PayCalculator, HourReporter, EmployeeRepositoryActor count → Violation confidence:
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)
# User: "Quick SRP check before commit"
# Skill runs level: fast (5s)
→ 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.
# User: "Review UserService for SRP compliance"
# Skill runs level: thorough (30s)
→ 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
# User: "Plan refactoring for PaymentProcessor - full SRP analysis"
# Skill runs level: full (5 min with user interaction)
→ 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)
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.
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.
SRP validation can be added as an optional quality gate in .claude/quality-gates.json:
{
"optional_gates": ["srp_validation"],
"srp_threshold": "warning"
}
Set threshold to "critical" to block commits on violations.
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.
| Parameter | Type | Default | Description |
|---|---|---|---|
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:
# Default (thorough mode on src/)
Skill(command: "validate-srp")
# Custom path and level
Skill(command: "validate-srp --path=src/application --level=full")
# JSON output for tooling integration
Skill(command: "validate-srp --output_format=json")
See Step 8 in Instructions for complete example.
{
"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
}
]
}
| Metric | Target | Benefit |
|---|---|---|
| Detection accuracy | >85% | Minimal false positives |
| God class detection | 100% | Catch all critical violations |
| False positive rate | <15% | High signal-to-noise ratio |
| Execution time | <30s | Fast enough for workflow |
| Actionability | 100% | Every violation has specific fix |
| Refactoring estimate accuracy | ±30% | Reliable planning |
Main validation script with multi-level analysis:
# Fast check (naming patterns only - 5 seconds)
./scripts/validate-srp.sh src/ --level=fast
# Thorough check (naming + size + constructors - 30 seconds)
./scripts/validate-srp.sh src/ --level=thorough
# Full analysis (with actor questions - 5 minutes)
./scripts/validate-srp.sh src/ --level=full
# JSON output for CI/CD integration
./scripts/validate-srp.sh src/ --output-format=json
Focused God Class detection for single files:
# Check specific file
./scripts/check-god-class.sh src/services/user_service.py
# Returns:
# - Constructor parameter count
# - Method count
# - File size
# - God Class recommendation
Minimum:
Optional:
radon for accurate metrics: uv pip install radonmcp__ast-grep__* tools for precise AST analysismcp__project-watch-mcp__search_code for contextInstallation:
# Make scripts executable
chmod +x scripts/*.sh
# Optional: Install radon for accurate metrics
uv pip install radon
# Verify installation
uv run radon --version
Symptom: Small helper methods flagged as violations
Fix: Adjust thresholds in .claude/srp-config.json:
{
"thresholds": {
"class_lines": 400,
"method_lines": 75,
"constructor_params": 6
}
}
Symptom: "Metrics unavailable" in report
Fix: Install radon:
uv pip install radon
Or use simplified heuristics (less accurate but faster).
Symptom: Actor analysis unclear
Fix: Ask targeted questions:
| Metric | Without SRP Validation | With SRP Validation | Improvement |
|---|---|---|---|
| God classes in codebase | 15-25 | 0-2 | 95% reduction |
| Time to understand class | 20-45 min | 5-10 min | 75% faster |
| Bugs per class | 8-12 per year | 1-3 per year | 85% reduction |
| Refactoring cost | High (embedded violations) | Low (caught early) | 80% reduction |
| Test coverage | 40-60% (hard to test) | 80-95% (easy to test) | 50% increase |
| Code review time | 30-60 min | 10-20 min | 66% faster |
Last Updated: 2025-11-02 Version: 1.0.0
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience