---
name: refactor-suggestions
description: Intelligent refactoring that asks about goals, analyzes code patterns, and automatically applies improvements while maintaining functionality.
isolation: worktree
---

# refactor-suggestions

Intelligent refactoring that asks about goals, analyzes code patterns, and automatically applies improvements while maintaining functionality.

## Usage

Ask me to refactor your code. I'll understand your goals, analyze patterns, and automatically apply improvements.

## Interactive Refactoring Goals

### Refactoring Questions

```
Q1: What's your refactoring goal?
   - Improve readability
   - Reduce complexity
   - Enhance performance
   - Modernize code
   - All improvements

Q2: Risk tolerance?
   - Conservative (minimal changes)
   - Moderate (balanced approach)
   - Aggressive (maximum improvement)

Q3: Target areas?
   - Components only
   - Business logic
   - Data layer
   - Entire codebase

Q4: Preserve what?
   - Public APIs
   - File structure
   - Variable names
   - Everything external

Q5: Testing approach?
   - Run tests after each change
   - Test at the end
   - Generate new tests
   - Trust the refactoring
```

## Automatic Refactoring Patterns

### 1. Component Optimization

```typescript
// BEFORE: Class component with lifecycle methods
class UserProfile extends React.Component {
  constructor(props) {
    super(props);
    this.state = { user: null, loading: true };
  }

  componentDidMount() {
    this.fetchUser();
  }

  fetchUser = async () => {
    const user = await api.getUser(this.props.id);
    this.setState({ user, loading: false });
  }

  render() {
    if (this.state.loading) return <Spinner />;
    return <div>{this.state.user.name}</div>;
  }
}

// AFTER: Functional component with hooks
function UserProfile({ id }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUser = async () => {
      const userData = await api.getUser(id);
      setUser(userData);
      setLoading(false);
    };
    fetchUser();
  }, [id]);

  if (loading) return <Spinner />;
  return <div>{user.name}</div>;
}

// AFTER AFTER: Custom hook extraction
function useUser(id) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUser = async () => {
      const userData = await api.getUser(id);
      setUser(userData);
      setLoading(false);
    };
    fetchUser();
  }, [id]);

  return { user, loading };
}

function UserProfile({ id }) {
  const { user, loading } = useUser(id);

  if (loading) return <Spinner />;
  return <div>{user.name}</div>;
}
```

### 2. Logic Simplification

```typescript
// BEFORE: Complex nested logic
function calculatePrice(item, user, coupon) {
  let price = item.basePrice;

  if (user.isPremium) {
    if (item.category === "electronics") {
      price = price * 0.8;
    } else if (item.category === "books") {
      price = price * 0.9;
    }
  } else {
    if (item.category === "electronics") {
      price = price * 0.95;
    }
  }

  if (coupon) {
    if (coupon.type === "percentage") {
      price = price * (1 - coupon.value / 100);
    } else {
      price = price - coupon.value;
    }
  }

  return price;
}

// AFTER: Strategy pattern with composition
const discountStrategies = {
  premium: {
    electronics: 0.8,
    books: 0.9,
    default: 1.0,
  },
  regular: {
    electronics: 0.95,
    default: 1.0,
  },
};

const applyCoupon = (price, coupon) => {
  if (!coupon) return price;

  return coupon.type === "percentage"
    ? price * (1 - coupon.value / 100)
    : price - coupon.value;
};

function calculatePrice(item, user, coupon) {
  const userType = user.isPremium ? "premium" : "regular";
  const discount =
    discountStrategies[userType][item.category] ||
    discountStrategies[userType].default;

  const discountedPrice = item.basePrice * discount;
  return applyCoupon(discountedPrice, coupon);
}
```

### 3. Data Structure Optimization

```typescript
// BEFORE: Inefficient array operations
function processOrders(orders) {
  const results = [];

  for (let i = 0; i < orders.length; i++) {
    const order = orders[i];
    if (order.status === "pending") {
      const user = users.find((u) => u.id === order.userId);
      const items = [];

      for (let j = 0; j < order.itemIds.length; j++) {
        const item = inventory.find((inv) => inv.id === order.itemIds[j]);
        items.push(item);
      }

      results.push({
        order,
        user,
        items,
      });
    }
  }

  return results;
}

// AFTER: Optimized with maps and functional approach
function processOrders(orders) {
  // Create lookup maps for O(1) access
  const userMap = new Map(users.map((u) => [u.id, u]));
  const inventoryMap = new Map(inventory.map((i) => [i.id, i]));

  return orders
    .filter((order) => order.status === "pending")
    .map((order) => ({
      order,
      user: userMap.get(order.userId),
      items: order.itemIds.map((id) => inventoryMap.get(id)),
    }));
}
```

## Refactoring Verification

```bash
#!/bin/bash
# verify-refactoring.sh

echo "🔄 Verifying Refactoring..."

# Backup original code
cp -r src src.backup

# Apply refactoring
node refactor.js

# Run tests
if npm test; then
  echo "✅ Tests passing after refactoring"
else
  echo "❌ Tests failing, rolling back"
  rm -rf src
  mv src.backup src
  exit 1
fi

# Check performance
node benchmark.js > perf-after.txt
if [ $(cat perf-after.txt) -lt $(cat perf-before.txt) ]; then
  echo "✅ Performance improved"
else
  echo "⚠️ Performance degraded"
fi

# Check bundle size
npm run build
if [ $(stat -f%z dist/bundle.js) -lt $(cat size-before.txt) ]; then
  echo "✅ Bundle size reduced"
fi

echo "🎉 Refactoring successful!"
```

## Refactoring Metrics

```javascript
const metrics = {
  before: {
    complexity: 42,
    duplication: 18,
    linesOfCode: 3420,
    testCoverage: 76,
  },
  after: {
    complexity: 23, // -45% reduction
    duplication: 3, // -83% reduction
    linesOfCode: 2150, // -37% reduction
    testCoverage: 94, // +24% increase
  },
  improvements: {
    readability: "+40%",
    performance: "+25%",
    maintainability: "+60%",
    bundleSize: "-30%",
  },
};
```

## Smart Refactoring Decisions

### Pattern Detection

```javascript
// Automatically detect and fix code smells
const codeSmells = {
  longMethod: (method) => method.lines > 20,
  largeClass: (cls) => cls.methods > 10,
  longParameterList: (func) => func.params > 3,
  duplicateCode: (blocks) => blocks.similarity > 0.8,
  deadCode: (code) => code.referenced === false,
};

// Apply appropriate refactoring
const refactorings = {
  longMethod: extractMethod,
  largeClass: extractClass,
  longParameterList: introduceParameterObject,
  duplicateCode: extractSharedFunction,
  deadCode: removeCode,
};
```

## Example Output

```
🔄 Refactoring Analysis Started

Your preferences:
✓ Goal: Reduce complexity
✓ Risk: Moderate
✓ Target: Components
✓ Preserve: Public APIs

Analyzing code patterns...
✓ Found 12 class components → Convert to functional
✓ Found 8 complex methods → Simplify logic
✓ Found 5 duplicate blocks → Extract utilities
✓ Found 3 unused exports → Remove dead code

Applying refactorings...
✅ Converted UserProfile to functional component
✅ Extracted useUser custom hook
✅ Simplified calculatePrice with strategy pattern
✅ Optimized processOrders from O(n²) to O(n)
✅ Removed 420 lines of dead code
✅ Combined 5 similar functions into 1 generic

Running verification...
✅ All 195 tests passing
✅ Performance improved by 25%
✅ Bundle size reduced by 30%
✅ No breaking changes detected

📊 Refactoring Summary:
- Complexity: 42 → 23 (-45%)
- Lines of code: 3420 → 2150 (-37%)
- Test coverage: 76% → 94% (+18%)
- Performance: +25% faster
- Bundle size: -30% smaller

Code quality grade: B → A 🎉
```
