Systematic code refactoring skill that transforms complex, hard-to-understand code into clear, well-documented, maintainable code while preserving correctness. Use when users request "readable", "maintainable", or "clean" code, during code reviews flagging comprehension issues, for legacy code modernization, or in educational/onboarding contexts. Applies structured refactoring patterns with validation.
Transforms complex Python code into clear, maintainable code using systematic refactoring patterns while preserving correctness.
/plugin marketplace add acaprino/alfio-claude-plugins/plugin install python-development@alfio-claude-pluginsThis skill inherits all available tools. When active, it can use any tool Claude has access to.
README.mdassets/pyproject.tomlassets/templates/analysis_template.mdassets/templates/flake8_report_template.mdassets/templates/summary_template.mdreferences/REGRESSION_PREVENTION.mdreferences/anti-patterns.mdreferences/cognitive_complexity_guide.mdreferences/examples/python_complexity_reduction.mdreferences/examples/script_to_oop_transformation.mdreferences/examples/typescript_naming_improvements.mdreferences/flake8_plugins_guide.mdreferences/oop_principles.mdreferences/patterns.mdscripts/analyze_multi_metrics.pyscripts/analyze_with_flake8.pyscripts/benchmark_changes.pyscripts/check_documentation.pyscripts/compare_flake8_reports.pyscripts/compare_metrics.pyTransform complex, hard-to-understand Python code into clear, well-documented, maintainable code while preserving correctness. This skill guides systematic refactoring that prioritizes human comprehension without sacrificing correctness or reasonable performance.
Invoke this skill when:
global statements, no clear module/class organization, configuration mixed with business logicDo NOT invoke this skill when:
Follow these principles in priority order:
ALWAYS observe these constraints:
flake8 --select=F821,E0602 before tests to catch NameErrors immediatelyRefactoring must NEVER introduce technical, logical, or functional regressions.
Read and apply references/REGRESSION_PREVENTION.md before any refactoring session.
Before each refactoring session:
After each micro-change (not at the end, EVERY SINGLE ONE):
flake8 --select=F821,E999 -> 0 errorspytest -x -> all passingIf ANY check fails: STOP -> REVERT -> ANALYZE -> FIX APPROACH -> RETRY
ANY REGRESSION = TOTAL FAILURE OF THE REFACTORING
Execute refactoring in four phases with validation at each step.
Before making any changes, analyze the code comprehensively:
references/anti-patterns.md):
references/oop_principles.md):
scripts/measure_complexity.py or scripts/analyze_multi_metrics.pyassets/templates/analysis_template.md)Output: Prioritized list of issues by impact and risk.
Plan the refactoring approach systematically with safety-by-design:
Identify changes by type:
For DESTRUCTIVE changes - CREATE MIGRATION PLAN (MANDATORY):
Risk assessment for each proposed change (Low/Medium/High)
Dependency identification - What else depends on this code?
Test strategy - What tests are needed? What might break?
Change ordering - Sequence changes from safest to riskiest
Expected outcomes - Document what metrics should improve and by how much
Output: Refactoring plan with sequenced changes, migration plans for destructive changes, test strategy, and rollback plan.
Apply refactoring patterns using safety-by-design workflow.
references/examples/script_to_oop_transformation.mdOutput: Refactored code passing all tests with clear commit history.
Validate improvements objectively:
Run static analysis FIRST (catch errors before tests):
flake8 <file> --select=F821,E0602 # Undefined names/variables
flake8 <file> --select=F401 # Unused imports
flake8 <file> # Full quality check
MANDATORY: Zero F821 and E0602 errors required
Run full test suite - 100% pass rate required
Validate architecture improvements:
references/oop_principles.md)Compare before/after metrics using scripts/measure_complexity.py or scripts/analyze_multi_metrics.py
Performance regression check - Run scripts/benchmark_changes.py for hot paths
Generate summary report using format from assets/templates/summary_template.md
Flag for human review if:
Output: Comprehensive validation report with test results, metrics comparison, performance benchmarks, and quality summary.
Apply these patterns systematically. See references/patterns.md for full catalog with examples.
references/patterns.mdSee references/cognitive_complexity_guide.md for cognitive complexity calculation rules and reduction patterns.
is_active/has_permission/can_edit, collections as pluralscalculate_total, validate_email), boolean queries as is_valid()/has_items()UPPERCASE_WITH_UNDERSCORES, replace magic numbers/stringsUserAccount, PaymentProcessor)For transforming script-like code to structured OOP. See references/examples/script_to_oop_transformation.md for a complete guide and references/oop_principles.md for SOLID principles.
See references/anti-patterns.md for the full catalog. Priority order:
Critical: Script-like/procedural code with global state, God Object/God Class High: Complex nested conditionals (>3 levels), long functions (>30 lines), magic numbers, cryptic names, missing type hints, missing docstrings Medium: Duplicate code, primitive obsession, long parameter lists (>5) Low: Inconsistent naming, redundant comments, unused imports
pip install ruff complexipy radon wily
ruff check src/ # Fast linting (Rust, replaces flake8+plugins)
complexipy src/ --max-complexity-allowed 15 # Cognitive complexity (Rust)
radon mi src/ -s # Maintainability Index
See references/cognitive_complexity_guide.md for complete configuration (pyproject.toml, pre-commit hooks, GitHub Actions, CLI usage).
The scripts/analyze_with_flake8.py and scripts/compare_flake8_reports.py scripts use flake8. See references/flake8_plugins_guide.md for the curated plugin list.
Use scripts/analyze_multi_metrics.py to combine cognitive complexity (complexipy), cyclomatic complexity (radon), and maintainability index in a single report.
| Metric | Tool | Use |
|---|---|---|
| Cognitive Complexity | complexipy | Human comprehension |
| Cyclomatic Complexity | ruff (C901), radon | Test planning |
| Maintainability Index | radon | Overall code health |
Monitor trends over time, not just thresholds. See references/cognitive_complexity_guide.md for setup and CI integration.
See references/REGRESSION_PREVENTION.md for the full guide. Key traps:
Structure refactoring output using the template from assets/templates/summary_template.md. Include:
Escalation path: humanize → humanize-python-code → python-refactor (from safest to most thorough).
uv run ruff, uv run complexipy for tool executionWhen NOT to Refactor: Performance-critical optimized code (profile first), code scheduled for deletion, external dependencies (contribute upstream), stable legacy code nobody needs to modify.
Limitations: Cannot improve algorithmic complexity (that's algorithm change, not refactoring). Cannot add domain knowledge not in code/comments. Cannot guarantee correctness without tests. Code style preferences vary - adjust based on team conventions.
See references/examples/ for before/after examples:
script_to_oop_transformation.md - Complete transformation from script-like code to clean OOP architecturepython_complexity_reduction.md - Nested conditionals and long functionstypescript_naming_improvements.md - Variable and function naming patterns (cross-language reference)Refactoring is successful when:
Activates when the user asks about AI prompts, needs prompt templates, wants to search for prompts, or mentions prompts.chat. Use for discovering, retrieving, and improving prompts.
Search, retrieve, and install Agent Skills from the prompts.chat registry using MCP tools. Use when the user asks to find skills, browse skill catalogs, install a skill for Claude, or extend Claude's capabilities with reusable AI agent components.
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code, generative art, algorithmic art, flow fields, or particle systems. Create original algorithmic art rather than copying existing artists' work to avoid copyright violations.