ワンクリックで
code-refactoring
Code quality improvement, technical debt reduction, and refactoring patterns for maintainable software.
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
メニュー
Code quality improvement, technical debt reduction, and refactoring patterns for maintainable software.
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
SOC 職業分類に基づく
PersonalOS skill: account-management
API endpoint testing, mocking, and integration testing for robust API development.
Optimize images, icons, and design assets for performance, quality, and developer handoff
Plan, track, and optimize budgets to maximize value and financial performance
CI/CD pipeline optimization, build failures, and deployment automation for DevOps workflows.
Comprehensive code review with quality checks, best practices, and actionable feedback
| name | code-refactoring |
| description | Code quality improvement, technical debt reduction, and refactoring patterns for maintainable software. |
Systematic approaches to improving code quality, reducing technical debt, and maintaining software maintainability.
Guides you through code refactoring to improve code quality, readability, and maintainability without changing functionality.
Code Smells to Look For:
Refactoring Signals:
✓ Hard to understand at first glance
✓ Requires reading multiple files to understand one feature
✓ Changes in one area break other areas
✓ Difficult to test in isolation
✓ Takes too long to make simple changes
✓ Frequent bugs in certain areas
Before Refactoring:
Test First Approach:
# Write tests for current behavior (even buggy behavior)
def test_current_behavior():
result = buggy_function({"input": 42})
assert result == expected_output
Refactoring Strategy:
Refactoring Checklist:
✓ Tests written and passing
✓ Dependencies identified
✓ Refactoring steps planned
✓ Rollback strategy ready
✓ Estimated time and impact
Common Refactoring Techniques:
Extract Method:
# Before
def process_order(order):
if order.amount > 1000:
discount = order.amount * 0.1
tax = order.amount * 0.08
total = order.amount - discount + tax
else:
discount = 0
tax = order.amount * 0.08
total = order.amount - discount + tax
return total
# After
def process_order(order):
discount = calculate_discount(order.amount)
tax = calculate_tax(order.amount)
return order.amount - discount + tax
def calculate_discount(amount):
return amount * 0.1 if amount > 1000 else 0
def calculate_tax(amount):
return amount * 0.08
Extract Variable:
# Before
if user.age >= 18 and user.has_license and not user.suspended:
allow_driving()
# After
can_drive = user.age >= 18 and user.has_license and not user.suspended
if can_drive:
allow_driving()
Inline Variable:
# Before
result = calculate(x, y, z)
final = result
# After
final = calculate(x, y, z)
Replace Magic Number with Constant:
# Before
if len(items) > 50:
apply_bulk_discount()
# After
MAX_ITEMS_FOR_BULK = 50
if len(items) > MAX_ITEMS_FOR_BULK:
apply_bulk_discount()
Rename Variable/Method:
# Before
def d(u, p):
return u - p
# After
def calculate_discount(user_price, promo_code):
return user_price - promo_code
Verification Steps:
Verification Checklist:
✓ All tests pass
✓ No new bugs introduced
✓ Performance acceptable
✓ Code is more readable
✓ Documentation updated
✓ Code review completed
Break large methods into smaller, well-named methods.
When to Use:
Benefit: Each method does one thing well, easier to test and understand.
Replace complex conditional logic with polymorphism.
When to Use:
Benefit: Open-closed principle, easier to add new types.
Move related methods and variables to a new class.
When to Use:
Benefit: Single responsibility principle, better organization.
Works With:
Gradual Refactoring Strategy:
1. Identify target area (module, system)
2. Create abstraction layer around legacy code
3. Write new implementation behind abstraction
4. Gradually migrate callers to new code
5. Remove legacy code when all migrated
Strangler Pattern:
# Old API
def legacy_function(data):
# Complex legacy code
pass
# New implementation
def new_function(data):
# Clean, new code
pass
# Abstraction layer
def function(data):
if use_legacy():
return legacy_function(data)
else:
return new_function(data)
TDD Refactoring Cycle:
1. Write test for existing behavior (capture bugs if present)
2. Verify test passes (or captures bug)
3. Refactor code
4. Verify test still passes
5. Commit
6. Repeat
Characterization Tests:
# Tests that document current behavior (even bugs)
def test_characterization():
input = {"value": 42}
output = legacy_function(input)
assert output == "current_output" # Document current behavior
Profiling First:
1. Profile code to identify bottlenecks
2. Measure current performance (baseline)
3. Optimize identified bottleneck
4. Measure improvement
5. Verify correctness
6. Document performance characteristics
Common Optimizations:
Example:
# Before - O(n²)
def find_duplicates_slow(items):
duplicates = []
for i, item1 in enumerate(items):
for j, item2 in enumerate(items):
if i != j and item1 == item2:
duplicates.append(item1)
return duplicates
# After - O(n)
def find_duplicates_fast(items):
seen = set()
duplicates = []
for item in items:
if item in seen:
duplicates.append(item)
seen.add(item)
return duplicates
Monolith to Microservices:
1. Identify bounded contexts
2. Create service boundaries
3. Extract services gradually
4. Implement communication (API, events)
5. Migrate data ownership
6. Decommission monolith components
Layered Architecture:
Presentation Layer (UI, API)
↓
Application Layer (Business Logic)
↓
Domain Layer (Core Business Rules)
↓
Infrastructure Layer (Database, External Services)
Common Database Refactorings:
Migration Strategy:
-- Step 1: Add new column
ALTER TABLE users ADD COLUMN email_new VARCHAR(255);
-- Step 2: Migrate data
UPDATE users SET email_new = email;
-- Step 3: Verify data
SELECT COUNT(*) FROM users WHERE email_new IS NULL;
-- Step 4: Update application to use new column
-- Deploy application
-- Step 5: Remove old column
ALTER TABLE users DROP COLUMN email;
Martin Fowler's Rules:
Code Quality Metrics:
Technical Debt Metrics:
Automated Refactoring Tools:
Examples:
# Python formatter
black .
# JavaScript formatter
prettier --write "**/*.js"
# Linter
eslint "**/*.js"
Multi-Skill Workflows:
1. Use code-review to identify refactoring candidates
2. Use debugging to understand behavior before refactoring
3. Use testing to ensure safety
4. Use code-refactoring to improve code
5. Use code-review again to verify improvements
6. Use workflow-orchestrator to automate repetitive refactorings
Predict Refactoring Candidates:
Implementation:
1. Track metrics over time
2. Identify trends (increasing complexity, decreasing quality)
3. Predict areas that will need refactoring
4. Refactor proactively before issues arise
Risk Indicators:
AI-Powered Refactoring:
1. Analyze code patterns and best practices
2. Identify refactoring opportunities
3. Suggest specific refactorings
4. Show potential benefits
5. Provide automated transformations
Example Suggestions:
Building a Refactoring Knowledge Graph:
1. Document all refactorings performed
2. Link refactorings to code patterns
3. Tag by type, impact, frequency
4. Enable semantic search for refactoring patterns
5. Learn from refactoring history
Knowledge Base Schema:
{
"refactoring_id": "REF-123",
"type": "extract_method",
"code_pattern": "long_method",
"impact": "improved_readability",
"location": "payment-service",
"benefit": "reduced_complexity",
"test_coverage": "maintained",
"related_refactorings": ["REF-100", "REF-200"]
}
Legacy Code Strategies:
Golden Master Testing:
# Run legacy system with many inputs
# Capture all outputs (golden master)
# Refactor code
# Run with same inputs, compare outputs
# Ensure outputs match
Event-Driven Architecture:
1. Identify events in domain
2. Design event schemas
3. Implement event producers
4. Implement event consumers
5. Add event sourcing if needed
6. Migrate gradually
CQRS (Command Query Responsibility Segregation):
1. Separate read and write models
2. Use different databases if needed
3. Update commands modify write model
4. Read queries from optimized read model
5. Keep models synchronized via events
Zero-Downtime Migration:
1. Add new column/table alongside old
2. Write to both old and new
3. Backfill data
4. Update application to read from new
5. Deploy application
6. Stop writing to old
7. Remove old
Schema Versioning:
# Versioned schema migrations
migrations = [
{"version": "1.0.0", "script": "migration_001.sql"},
{"version": "1.0.1", "script": "migration_002.sql"},
{"version": "1.1.0", "script": "migration_003.sql"},
]
Boy Scout Rule: "Leave the code better than you found it."
Continuous Improvement:
Learning from Code:
Tracking Refactoring Impact:
- Bug rate before/after refactoring
- Development time before/after refactoring
- Test coverage changes
- Code complexity trends
- Team velocity changes
- Developer satisfaction
Do:
Don't:
Before:
def calculate_price(user, product, quantity):
if user.is_vip:
if product.category == "electronics":
if quantity > 10:
return product.price * quantity * 0.85
else:
return product.price * quantity * 0.90
else:
if quantity > 10:
return product.price * quantity * 0.90
else:
return product.price * quantity * 0.95
else:
if product.category == "electronics":
if quantity > 10:
return product.price * quantity * 0.95
else:
return product.price * quantity * 0.98
else:
if quantity > 10:
return product.price * quantity * 0.97
else:
return product.price * quantity * 1.0
After (Polymorphism):
class PricingStrategy:
def get_discount(self, product, quantity):
pass
class VIPPricingStrategy(PricingStrategy):
def get_discount(self, product, quantity):
if product.category == "electronics":
return 0.15 if quantity > 10 else 0.10
else:
return 0.10 if quantity > 10 else 0.05
class RegularPricingStrategy(PricingStrategy):
def get_discount(self, product, quantity):
if product.category == "electronics":
return 0.05 if quantity > 10 else 0.02
else:
return 0.03 if quantity > 10 else 0.0
def calculate_price(user, product, quantity):
strategy = VIPPricingStrategy() if user.is_vip else RegularPricingStrategy()
discount = strategy.get_discount(product, quantity)
return product.price * quantity * (1 - discount)
Before:
class OrderProcessor:
def __init__(self):
self.user_database = Database("users")
self.product_database = Database("products")
self.payment_processor = PaymentProcessor()
self.email_service = EmailService()
self.inventory_service = InventoryService()
def process_order(self, order):
user = self.user_database.get(order.user_id)
product = self.product_database.get(order.product_id)
if not product.in_stock:
raise OutOfStockError()
if user.balance < product.price:
raise InsufficientFundsError()
payment = self.payment_processor.charge(
user.payment_method,
product.price
)
self.inventory_service.reduce_stock(product.id, 1)
self.email_service.send(
user.email,
"Order Confirmation",
f"Your order {order.id} is confirmed"
)
return payment
After:
class OrderProcessor:
def __init__(self, payment_gateway, inventory, email):
self.payment_gateway = payment_gateway
self.inventory = inventory
self.email = email
def process_order(self, order, user, product):
self.inventory.check_availability(product)
self.payment_gateway.charge(user, product.price)
self.inventory.reduce_stock(product, 1)
self.email.send_confirmation(user, order)
class Inventory:
def check_availability(self, product):
if not product.in_stock:
raise OutOfStockError()
def reduce_stock(self, product, quantity):
# Reduce stock logic
pass
class PaymentGateway:
def charge(self, user, amount):
if user.balance < amount:
raise InsufficientFundsError()
# Charge logic
pass
class EmailService:
def send_confirmation(self, user, order):
self.email_service.send(
user.email,
"Order Confirmation",
f"Your order {order.id} is confirmed"
)
Before (Denormalized):
CREATE TABLE orders (
id INT PRIMARY KEY,
user_name VARCHAR(255),
user_email VARCHAR(255),
user_address VARCHAR(255),
product_name VARCHAR(255),
product_price DECIMAL(10, 2),
quantity INT,
total DECIMAL(10, 2)
);
After (Normalized):
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255),
address VARCHAR(255)
);
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(255),
price DECIMAL(10, 2)
);
CREATE TABLE orders (
id INT PRIMARY KEY,
user_id INT,
product_id INT,
quantity INT,
total DECIMAL(10, 2),
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);
Problem: No safety net, risk of breaking functionality Fix: Always write tests before refactoring
Problem: Hard to identify if bugs are from refactoring or new code Fix: Keep refactoring separate from adding features
Problem: Hard to rollback, hard to identify what caused issues Fix: Make small, incremental changes
Problem: Changes may break edge cases or hidden dependencies Fix: Spend time understanding code before refactoring
Problem: Bugs introduced, performance degraded Fix: Run tests, check performance, review with team
Problem: Too much abstraction, code becomes harder to understand Fix: Refactor for clarity, not just for abstraction
Problem: Team doesn't understand changes, same issues recur Fix: Document refactorings, reasons, and lessons learned
A: Write comprehensive tests first. Tests provide a safety net and ensure refactoring doesn't change behavior.
A: Stop when the code is clean, understandable, and maintainable. Don't over-engineer or refactor just for the sake of it.
A: Apply the Boy Scout Rule: make small improvements when you touch the code. Schedule dedicated refactoring time for larger improvements.
A: Yes, but be careful. Use wrapping strategies, write characterization tests, and refactor gradually.
A: Show the impact of technical debt (bugs, slower development). Track metrics to show improvement. Refactor incrementally to minimize risk.