code-refactoring-refactor-clean
You are a code refactoring expert specializing in clean code principles, SOLID design patterns, and modern software engineering best practices. Analyze and refactor the provided code to improve its quality, maintainability, and performance.
About this skill
This skill transforms an AI agent into a dedicated code refactoring specialist. It enables the agent to meticulously analyze provided code snippets or larger blocks, identifying areas for improvement based on established clean code principles, SOLID design patterns (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion), and contemporary software engineering best practices. The primary objective is to enhance code quality, boost maintainability, optimize performance, and improve readability, ensuring the codebase is robust, scalable, and easy to understand for future development.
Best use case
Automating the refactoring of complex or legacy codebases, resolving code smells, reducing technical debt, and standardizing code design across projects to improve overall software health and developer productivity.
You are a code refactoring expert specializing in clean code principles, SOLID design patterns, and modern software engineering best practices. Analyze and refactor the provided code to improve its quality, maintainability, and performance.
A refactored version of the provided code that adheres to clean code principles, exhibits better design patterns, is easier to maintain and test, has reduced complexity, and potentially improved performance. The output will typically include the revised code, along with detailed explanations of the changes made and the rationale behind them.
Practical example
Example input
```python
def calculate_total_price(items, discount_percentage):
total = 0
for item in items:
total += item['price'] * item['quantity']
if discount_percentage > 0:
discount_amount = total * (discount_percentage / 100)
total -= discount_amount
if total < 0:
total = 0 # Ensure total is not negative after discounts
return total
```Example output
```json
{
"refactored_code": "class Item:\n def __init__(self, price: float, quantity: int):\n if price < 0 or quantity < 0:\n raise ValueError(\"Price and quantity cannot be negative\")\n self.price = price\n self.quantity = quantity\n\n def get_line_total(self) -> float:\n return self.price * self.quantity\n\nclass Order:\n def __init__(self, items: list[Item]):\n self.items = items\n\n def calculate_subtotal(self) -> float:\n return sum(item.get_line_total() for item in self.items)\n\n def apply_discount(self, total_amount: float, discount_percentage: float) -> float:\n if not (0 <= discount_percentage <= 100):\n raise ValueError(\"Discount percentage must be between 0 and 100.\")\n
discount_amount = total_amount * (discount_percentage / 100)\n return max(0.0, total_amount - discount_amount)\n\ndef get_final_order_price(items_data: list[dict], discount_percentage: float) -> float:\n items = [Item(data['price'], data['quantity']) for data in items_data]\n order = Order(items)\n
subtotal = order.calculate_subtotal()\n final_price = order.apply_discount(subtotal, discount_percentage)\n
return final_price\n\n# Example Usage:\n# order_items_data = [{'price': 100, 'quantity': 2}, {'price': 50, 'quantity': 1}]\n# final_price = get_final_order_price(order_items_data, 10)\n# print(f\"Final price: {final_price}\") # Expected: 225.0\n",
"explanation_of_changes": [
"**Single Responsibility Principle (SRP):** The original function was doing too much. It's now decomposed into `Item` (for item details and line total), `Order` (for managing items, calculating subtotal, and applying discount), and a coordinating function `get_final_order_price`.",
"**Readability and Modularity:** Using classes makes the code more organized, self-documenting, and easier to test individual components.",
"**Input Validation:** Added validation in `Item` and `Order.apply_discount` to ensure valid inputs, preventing erroneous calculations.",
"**Clarity in Discount Logic:** The `apply_discount` method clearly encapsulates the discount calculation and ensures the total doesn't go below zero (using `max(0.0, ...)`).",
"**Improved Type Hinting:** Added type hints for better code understanding and maintainability, especially in larger codebases."
],
"identified_code_smells": [
"**Long Method:** The original `calculate_total_price` function had multiple responsibilities.",
"**Primitive Obsession:** Using raw dictionaries for 'items' without a dedicated class to encapsulate behavior and data.",
"**Conditional Complexity:** Nested `if` statements for discount and negative total handling made the single function less cohesive."
]
}
```When to use this skill
- When facing a codebase with high technical debt, poor readability, or significant complexity.
- To eliminate common code smells such as long methods, duplicate code, large classes, or feature envy.
- Prior to adding new features to an existing module to ensure the foundation is solid and extensible.
- During code reviews to suggest systematic improvements and enforce design patterns.
When not to use this skill
- For generating entirely new code from scratch, as its focus is on improving existing code.
- When the primary goal is debugging runtime errors without an explicit need for structural or quality improvements.
- For high-level architectural design of new systems or complete system overhauls that require human-level strategic planning beyond code-level refactoring.
- On highly performance-critical sections where even minor changes could have significant, unintended consequences without rigorous testing.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/code-refactoring-refactor-clean/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How code-refactoring-refactor-clean Compares
| Feature / Agent | code-refactoring-refactor-clean | Standard Approach |
|---|---|---|
| Platform Support | Claude | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
You are a code refactoring expert specializing in clean code principles, SOLID design patterns, and modern software engineering best practices. Analyze and refactor the provided code to improve its quality, maintainability, and performance.
Which AI agents support this skill?
This skill is designed for Claude.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# Refactor and Clean Code You are a code refactoring expert specializing in clean code principles, SOLID design patterns, and modern software engineering best practices. Analyze and refactor the provided code to improve its quality, maintainability, and performance. ## Use this skill when - Refactoring tangled or hard-to-maintain code - Reducing duplication, complexity, or code smells - Improving testability and design consistency - Preparing modules for new features safely ## Do not use this skill when - You only need a small one-line fix - Refactoring is prohibited due to change freeze - The request is for documentation only ## Context The user needs help refactoring code to make it cleaner, more maintainable, and aligned with best practices. Focus on practical improvements that enhance code quality without over-engineering. ## Requirements $ARGUMENTS ## Instructions - Assess code smells, dependencies, and risky hotspots. - Propose a refactor plan with incremental steps. - Apply changes in small slices and keep behavior stable. - Update tests and verify regressions. - If detailed patterns are required, open `resources/implementation-playbook.md`. ## Safety - Avoid changing external behavior without explicit approval. - Keep diffs reviewable and ensure tests pass. ## Output Format - Summary of issues and target areas - Refactor plan with ordered steps - Proposed changes and expected impact - Test/verification notes ## Resources - `resources/implementation-playbook.md` for detailed patterns and examples.
Related Skills
n8n-expression-syntax
Validate n8n expression syntax and fix common errors. Use when writing n8n expressions, using {{}} syntax, accessing $json/$node variables, troubleshooting expression errors, or working with webhook data in workflows.
mermaid-expert
Create Mermaid diagrams for flowcharts, sequences, ERDs, and architectures. Masters syntax for all diagram types and styling.
mcp-builder-ms
Use this skill when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).
makepad-deployment
CRITICAL: Use for Makepad packaging and deployment. Triggers on: deploy, package, APK, IPA, 打包, 部署, cargo-packager, cargo-makepad, WASM, Android, iOS, distribution, installer, .deb, .dmg, .nsis, GitHub Actions, CI, action, marketplace
macos-menubar-tuist-app
Build, refactor, or review SwiftUI macOS menubar apps that use Tuist.
kaizen
Guide for continuous improvement, error proofing, and standardization. Use this skill when the user wants to improve code quality, refactor, or discuss process improvements.
issues
Interact with GitHub issues - create, list, and view issues.
hugging-face-tool-builder
Your purpose is now is to create reusable command line scripts and utilities for using the Hugging Face API, allowing chaining, piping and intermediate processing where helpful. You can access the API directly, as well as use the hf command line tool.
git-pushing
Stage all changes, create a conventional commit, and push to the remote branch. Use when explicitly asks to push changes ("push this", "commit and push"), mentions saving work to remote ("save to github", "push to remote"), or completes a feature and wants to share it.
git-hooks-automation
Master Git hooks setup with Husky, lint-staged, pre-commit framework, and commitlint. Automate code quality gates, formatting, linting, and commit message enforcement before code reaches CI.
gh-review-requests
Fetch unread GitHub notifications for open PRs where review is requested from a specified team or opened by a team member. Use when asked to "find PRs I need to review", "show my review requests", "what needs my review", "fetch GitHub review requests", or "check team review queue".
fp-types-ref
Quick reference for fp-ts types. Use when user asks which type to use, needs Option/Either/Task decision help, or wants fp-ts imports.