---
name: refactoring
description: Code refactoring patterns, code smells, and safe transformation techniques. Use when improving existing code.
---

# Refactoring Skill

## Safe Refactoring Process
1. **Ensure tests exist** for the code being changed
2. **Make one change at a time** - small, incremental steps
3. **Run tests after each change**
4. **Commit frequently** - easy to revert

## Common Code Smells
| Smell | Fix |
|-------|-----|
| Long function (>30 lines) | Extract methods |
| Long parameter list (>3) | Introduce parameter object |
| Duplicate code | Extract shared function |
| Deep nesting (>3 levels) | Early returns, extract method |
| Magic numbers | Named constants |
| God class | Split into focused classes |
| Feature envy | Move method to data's class |
| Dead code | Delete it |

## Refactoring Techniques
```python
# 1. Extract Method
# Before
def process(data):
    # validate
    if not data: raise ValueError()
    if len(data) > 100: raise ValueError()
    # ... 50 more lines

# After
def process(data):
    validate(data)
    transform(data)
    save(data)

# 2. Replace Conditionals with Polymorphism
# Before
if type == "email": send_email(msg)
elif type == "sms": send_sms(msg)

# After
notifiers = {"email": EmailNotifier, "sms": SMSNotifier}
notifiers[type]().send(msg)

# 3. Introduce Parameter Object
# Before
def create_user(name, email, age, role, department):

# After
@dataclass
class UserData:
    name: str
    email: str
    age: int
    role: str
    department: str

def create_user(data: UserData):
```
