# Refactoring and Migrating — AI Coding Assistants: Use Them Well and Review Them Hard

Source: https://www.geekswithgeeks.com/en/ai-coding-assistants/flow-refactor

> Use assistants for mechanical changes while tests guard behaviour.

## Change structure, keep behaviour

**Refactoring** changes how code is organised without changing what it does: renaming, extracting functions, converting callbacks to `async`/`await`, upgrading a library API, moving JavaScript to TypeScript. Assistants are good at these repetitive transformations. The safety net is a **passing test suite before and after**; without tests, a refactor can quietly change behaviour. Do it in small commits so each step can be reviewed.

## Checking behaviour is preserved

Run the same checks before and after the change. Only commit when both are green and the diff reads as intended.

```bash
npm test                       # green BEFORE
# ... let the assistant refactor ...
npm test                       # must still be green AFTER
git diff --stat                # how many files changed?
git diff                       # read every changed line
```

## Refactor and add features separately

Mixing a structural change with new behaviour in one commit makes bugs hard to trace. Refactor first with tests green, commit, then change behaviour in a separate step.

**Quiz:** What protects behaviour during an AI-assisted refactor?

- [ ] Hoping nothing changed
- [x] A passing test suite before and after
- [ ] A longer prompt
- [ ] Deleting old tests

*Answer:* A passing test suite before and after. Tests detect accidental behaviour changes that a diff alone may not reveal.
