code-refactoring
Skill9 starsChanged 3 months agoMITView on GitHub
Code refactoring patterns and techniques for improving code quality without changing behavior. Use for cleaning up legacy code, reducing complexity, or improving maintainability.
5 other projects use a version of this, 1 of them edited.
Adopted by
Most recently taken up by
- joabgonzalez/ai-agents-skillstheir own version, first seen Jun 8, 2026
- myths-labs/museedited, first seen Apr 10, 2026
- autohandai/community-skillstheir own version, first seen Mar 9, 2026
- DauQuangThanh/hanoi-rainbowtheir own version, first seen Jan 22, 2026
- Willhong/claude_skilltheir own version, first seen Nov 17, 2025
Other versions5 projects use a version of this.
Word for word · 0
None found.
Edited · 1
- myths-labs/muse★ 3536% same
Wrote their own version · 4
- DauQuangThanh/hanoi-rainbow★ 17same name
- autohandai/community-skills★ 11same name
- joabgonzalez/ai-agents-skills★ 9same name
- Willhong/claude_skill★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository13 other files it gives its agents.
- toolconfigs/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- toolconfigs/CLAUDE.mdCLAUDE.md
- toolconfigs/copilot-instructions.mdCopilot instructions
- parallel-sessionsSkill
- receiving-code-reviewSkill
- test-driven-developmentSkill
- visual-smokeSkill
- code-refactoringSkill
- dev-harness-for-ui-iterationSkill
- receiving-code-reviewSkill
- test-driven-developmentSkill
- visual-smokeSkill
The file
We split this skill into the rules it gives an agent
9 rules. 0 are common, 5 are distinctive, and 4 are very specific to this project.
0
Common
Most of the 5 edited versions we read keep these.
5
Distinctive
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 13
Before adding new features (make change easy, then make easy change)
- Distinctive: line 14
After getting tests passing (red-green-refactor)
- Distinctive: line 15
When you see code smells
- Distinctive: line 22
When you don't understand what the code does
- Very specific: line 204
Ensure tests exist: - Write tests if they don't (pytest to confirm they pass)
- Distinctive: line 208
Review the diff: - Make sure behavior hasn't changed
- Very specific: line 212
Use mypy or pyright for type checking after refactoring: rename regressions show up immediately.
- Very specific: line 214
Prefer @dataclass(frozen=True) for value objects over mutable classes.
- Very specific: line 215
Use Protocol instead of ABC when the interface is structural (duck typing): callers don't need to import or inherit from the protocol.
“Common” is measured: kept by at least 6 in 10 of the 5 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Code Refactoring
Refactoring Principles
When to Refactor
- Before adding new features (make change easy, then make easy change)
- After getting tests passing (red-green-refactor)
- When you see code smells
- During code review feedback
When NOT to Refactor
- Without tests covering the code
- Under tight deadlines with no safety net
- Code that will be replaced soon
- When you don't understand what the code does
Common Code Smells
Long Methods
# BEFORE: Method doing too much
def process_order(order: Order) -> None:
# 100 lines of validation, calculation, notification, logging...
# AFTER: Extract into focused methods
def process_order(order: Order) -> None:
validate_order(order)
total = calculate_total(order)
save_order(order, total)
notify_customer(order)Deeply Nested Conditionals
# BEFORE: Arrow code
def get_discount(user: User, order: Order) -> float:
if user:
if user.is_premium:
if order.total > 100:
if len(order.items) > 5:
return 0.2
return 0.0
# AFTER: Early returns (guard clauses)
def get_discount(user: User, order: Order) -> float:
if not user:
return 0.0
if not user.is_premium:
return 0.0
if order.total <= 100:
return 0.0
if len(order.items) <= 5:
return 0.0
return 0.2Primitive Obsession
# BEFORE: Primitives everywhere
def create_user(name: str, email: str, phone: str) -> User:
if '@' not in email:
raise ValueError('Invalid email')
# more validation...
# AFTER: Value objects
from dataclasses import dataclass
@dataclass(frozen=True)
class Email:
value: str
def __post_init__(self) -> None:
if '@' not in self.value:
raise ValueError('Invalid email')
def __str__(self) -> str:
return self.value
def create_user(name: str, email: Email, phone: Phone) -> User:
# Email is already validated
...Feature Envy
# BEFORE: Method uses another object's data extensively
def calculate_shipping(order: Order) -> float:
address = order.customer.address
weight = sum(item.weight for item in order.items)
distance = calculate_distance(address.zip_code)
return weight * distance * 0.01
# AFTER: Move method to where the data is
class Order:
def calculate_shipping(self) -> float:
return self.total_weight * self.customer.shipping_distance * 0.01Refactoring Techniques
Extract Method
# Identify a code block that does one thing
# Move it to a new function with a descriptive name
# Replace original code with the function call
def print_report(data: ReportData) -> None:
# Extract this block into a function
_print_header(data)
# ... rest of report
def _print_header(data: ReportData) -> None:
header = f"Report: {data.title}\nDate: {data.date}\n{'=' * 40}"
print(header)Replace Conditional with Polymorphism
# BEFORE: if/elif on type
def get_area(shape: Shape) -> float:
if shape.type == 'circle':
return math.pi * shape.radius ** 2
elif shape.type == 'rectangle':
return shape.width * shape.height
elif shape.type == 'triangle':
return shape.base * shape.height / 2
raise ValueError(f'Unknown shape: {shape.type}')
# AFTER: Polymorphic classes
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def get_area(self) -> float: ...
class Circle(Shape):
def __init__(self, radius: float) -> None:
self.radius = radius
def get_area(self) -> float:
return math.pi * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width: float, height: float) -> None:
self.width = width
self.height = height
def get_area(self) -> float:
return self.width * self.heightIntroduce Parameter Object
# BEFORE: Too many parameters
def search_products(
query: str,
min_price: float,
max_price: float,
category: str,
in_stock: bool,
sort_by: str,
sort_order: str,
) -> list[Product]: ...
# AFTER: Parameter object (dataclass or TypedDict)
from dataclasses import dataclass, field
@dataclass
class SearchParams:
query: str
price_range: tuple[float, float] = (0.0, float('inf'))
category: str | None = None
in_stock: bool | None = None
sort_by: str = 'relevance'
sort_order: str = 'asc'
def search_products(params: SearchParams) -> list[Product]: ...Replace Magic Numbers with Constants
# BEFORE
if user.age >= 18 and order.total >= 50:
apply_discount(order, 0.1)
# AFTER
MINIMUM_AGE = 18
DISCOUNT_THRESHOLD = 50.0
STANDARD_DISCOUNT = 0.1
if user.age >= MINIMUM_AGE and order.total >= DISCOUNT_THRESHOLD:
apply_discount(order, STANDARD_DISCOUNT)Safe Refactoring Process
- Ensure tests exist - Write tests if they don't (
pytestto confirm they pass) - Make small changes - One refactoring at a time
- Run tests after each change -
pytestto catch regressions immediately - Commit frequently - Easy to revert if something breaks
- Review the diff - Make sure behavior hasn't changed
Python-Specific Notes
- Use
mypyorpyrightfor type checking after refactoring: rename regressions show up immediately. ruffcan automate many simple refactors (unused imports, simplifiable conditionals).- Prefer
@dataclass(frozen=True)for value objects over mutable classes. - Use
Protocolinstead ofABCwhen the interface is structural (duck typing): callers don't need to import or inherit from the protocol. functools.lru_cache/functools.cachecan replace memoization boilerplate.
Refactoring Checklist
- Tests pass before starting (
pytest) - Each change is small and focused
- Tests pass after each change (
pytest) - Type checker passes (
mypy/pyright) - No behavior changes (only structure)
- Code is more readable than before
- Commit message explains the refactoring
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

