> ## Documentation Index
> Fetch the complete documentation index at: https://docs.blitzy.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Refactor Code

> Modernize existing code through systematic refactoring to reduce technical debt, improve architecture, and apply design patterns

Every codebase accumulates shortcuts, outdated patterns, and architectural drift that slow the team down over time. Refactoring that debt away is critical but rarely gets prioritized because it is high-effort and low-visibility. Blitzy handles the heavy lifting: it restructures code while preserving external behavior, applies modern design patterns, and validates equivalence so your team can modernize confidently instead of indefinitely.

<CardGroup cols={2}>
  <Card title="Refactor Template" icon="wrench" href="/templates/code-quality-maintenance/refactor">
    Use the **Refactor Template** for general code refactoring with a structured prompt
  </Card>
</CardGroup>

<Note>
  **Jump to:** [When to Use](#when-to-use-this-approach) | [Prompt Structure](#prompt-structure) | [Key Considerations](#key-considerations) | [Common Patterns](#common-patterns) | [Troubleshooting](#troubleshooting)
</Note>

## When to Use This Approach

<Tabs>
  <Tab title="Technical Debt Reduction">
    Clean up rushed implementations and architectural drift that make every change slower and riskier.
  </Tab>

  <Tab title="Legacy Modernization">
    Upgrade legacy code to current language features, frameworks, and idioms without rewriting from scratch.
  </Tab>

  <Tab title="Monolith Decomposition">
    Break apart tightly coupled systems into microservices or modular components with clear boundaries.
  </Tab>

  <Tab title="Performance Optimization">
    Improve algorithmic efficiency, reduce resource consumption, and prepare foundations for future feature work.
  </Tab>
</Tabs>

## Prompt Structure

Follow the [Golden Rules](/prompt-engineering/golden-rules) when writing your refactoring prompt. Focus especially on:

* **Objective Clarity** - Specify exact files, line ranges, and target architecture patterns
* **Behavioral Constraints** - Define what must remain unchanged (APIs, response formats, performance)
* **Reference Patterns** - Point to existing code demonstrating the architectural style to follow
* **Success Metrics** - Include measurable targets (performance, test coverage, maintainability)

<Warning>
  **Destination repository required for new-repo refactors** — For refactors that target a new repository (e.g., monolith-to-microservices extraction), the destination repository must already exist on your Git provider before starting the run. Blitzy pushes to existing repositories only — it cannot create new ones. See [GitHub Integration](/integrations/github) or [GitHub Enterprise Server Integration](/integrations/github-enterprise-server) for setup details.
</Warning>

## Key Considerations

<CardGroup cols={2}>
  <Card title="Test Coverage Is Mandatory" icon="vial-circle-check">
    Establish comprehensive automated tests before refactoring to validate behavioral equivalence. Without tests, you cannot verify the refactored code maintains identical functionality.
  </Card>

  <Card title="Behavioral Constraints Over Structure" icon="lock">
    Explicitly state what must remain unchanged (API contracts, response formats, performance characteristics) rather than describing how the refactored code should be structured.
  </Card>

  <Card title="Incremental Scope Prevents Risk" icon="layer-group">
    Break large refactorings into small, independently testable changes. Attempting to refactor entire subsystems in single PRs creates review bottlenecks and increases bug risk.
  </Card>

  <Card title="Performance Baselines Establish Success" icon="gauge-high">
    Measure current performance characteristics (latency, throughput, resource usage) before refactoring and define target metrics.
  </Card>
</CardGroup>

## Common Patterns

**Legacy API modernization** - Convert callback-based code to async/await while preserving identical API contracts, error handling, and response formats. Reference recently modernized controllers as patterns.

**Monolith decomposition** - Extract service boundaries from monolithic code, define clear API contracts between services, preserve existing external APIs, and add retry logic for inter-service communication.

**Design pattern application** - Replace ad-hoc implementations with established patterns (Strategy, Factory, Observer), extract pattern-specific classes, and maintain existing public interfaces while improving internal organization.

## Troubleshooting

<AccordionGroup>
  <Accordion title="Refactored code breaks existing tests">
    Tests may be validating implementation details rather than behavior. Update tests to focus on public interfaces and observable behavior while ensuring refactored code maintains identical outputs.
  </Accordion>

  <Accordion title="Performance degrades after refactoring">
    Benchmark before and after refactoring. Add the [Analyze Performance Impact](/templates/rules/analyze-performance-impact) rule to your project on the platform and specify performance targets explicitly (latency, throughput, resource usage).
  </Accordion>

  <Accordion title="Behavior changes subtly after refactoring">
    Add characterization tests before refactoring that capture current behavior, including edge cases. Verify all tests pass identically with refactored code before deployment.
  </Accordion>

  <Accordion title="Refactoring scope grows uncontrollably">
    Break into smaller incremental changes. Each refactoring should touch minimal files and be independently deployable. Use feature flags for gradual rollout.
  </Accordion>

  <Accordion title="Dependent systems break after refactoring">
    Map all dependencies before refactoring. Verify API contracts remain unchanged. Add integration tests validating interactions with dependent services remain identical.
  </Accordion>
</AccordionGroup>
