# Legacy Code Refactoring

- Section: Documentation > Use Cases > Legacy Code Refactoring
- Canonical: https://covdbg.com/docs/use-cases/legacy-refactoring/

---

Coverage is very useful when you refactor legacy C++ code and want to understand which code paths your current tests exercise.

## The Challenge

Legacy code refactoring is risky:

* Limited or no tests exist
* Original developers are gone
* Documentation is outdated
* Behavior is poorly understood

## Coverage as a Safety Net

Code coverage helps de-risk refactoring:

* Measure baseline - See what existing tests cover
* Identify gaps - Find untested high-risk areas
* Add tests first - Build safety net before changes
* Refactor with confidence - Tests catch regressions
* Verify coverage maintained - Ensure nothing is broken

## Baseline coverage

* Run your existing tests under covdbg and store a baseline database:

```powershell
covdbg --output "C:\path\to\baseline.covdb" "C:\path\to\existing_tests.exe"
```

* Export the baseline for reporting:

```powershell
covdbg convert --input "C:\path\to\baseline.covdb" --format LCOV --output "C:\path\to\baseline.lcov"
```

## Focus on the module you want to change

Put include/exclude filters into `.covdbg.yaml` so covdbg only tracks the module you are working on:

```yaml
version: 1
source_root: "."
coverage:
  default:
    files:
      include:
        - "legacy_module/**"
      exclude:
        - "build/**"
```

Then run:

```powershell
covdbg --config ".covdbg.yaml" --output "focused.covdb" "tests.exe"
```

## Incremental Testing Strategy

### Step 1: Establish Baseline

Run existing tests and record coverage:

```powershell
covdbg --output "baseline.covdb" "existing_tests.exe"
covdbg convert -i baseline.covdb -f LCOV -o baseline.lcov
```

### Step 2: Identify Critical Gaps

Export to LCOV and use coverage tools (e.g., lcov-viewer, genhtml) to find:
- Functions with 0% coverage (high risk)
- Complex functions with partial coverage
- Error handling paths never tested

### Step 3: Add Tests Incrementally

Write tests for uncovered areas, re-run coverage:

```powershell
# After adding new tests
covdbg --output "with_new_tests.covdb" "tests.exe"

# Compare coverage improvement
covdbg convert -i with_new_tests.covdb -f LCOV -o improved.lcov
```

### Step 4: Refactor with Confidence

With adequate coverage in place:
1. Make small, focused changes
2. Re-run tests to catch regressions
3. Verify coverage remains stable or improves

## Combining Multiple Test Types

Merge unit tests and manual testing coverage:

```powershell
# Unit tests
covdbg --output "unit.covdb" "unit_tests.exe"

# Integration/manual tests
covdbg --output "integration.covdb" "app.exe"

# Merge for complete picture
covdbg merge -i unit.covdb -i integration.covdb -o combined.covdb
```

## See Also

* [Configuration](/docs/reference/configuration/) - Filter patterns
* [Quick Start](/docs/getting-started/quick-start/) - Basic usage
