CMD Master
Back to Blog
Arnošt Havelka

Prompt Templates for Refactoring Code

Reusable AI prompt templates for safe refactoring that preserve behavior, limit scope, require tests, and define validation.

Prompt Templates for Refactoring Code

A safe refactoring prompt tells an AI coding assistant what behavior to preserve, where to work, which tests define the contract, and how to validate the result. “Clean this up” is not a refactoring plan. It is an invitation to change things you have not reviewed.

Use these templates as starting points. Replace the bracketed details with facts from your codebase, and ask for analysis before a broad change.

Template: safe refactoring

Refactor [component/module/function] to improve [specific maintainability
problem].

Behavior preservation: Keep [public API, visible behavior, events, error
handling, accessibility, performance characteristic] unchanged.

Scope: Limit changes to [files/boundary]. Do not change [explicit non-goals].

Tests: Identify the existing tests that prove the current contract. Add focused
regression coverage if a protected behavior is not covered.

Acceptance criteria: The duplication or coupling is reduced, public behavior is
unchanged, and the diff has no unrelated cleanup.

Validation: Run [focused test command], type check, and [manual workflow].
Before editing, describe the current contract and the smallest safe extraction.

Use this when you know the improvement but want to protect a stable feature boundary.

Template: extracting a component

Extract the repeated [UI region] from [parent components] into the smallest
reusable component.

Behavior preservation: Keep visible labels, keyboard focus, aria attributes,
loading state, analytics events, and mobile layout identical.

Scope: Only [parent components], the new component, and direct tests. Do not
move data fetching or mutation ownership into the extracted component.

Tests: Preserve or add tests for [empty, loading, error, populated] states and
the interactive behavior users rely on.

Acceptance criteria: The parents use the new component, the differing behavior
remains explicit, and no public props or links change unexpectedly.

Validation: Run focused component tests, inspect the rendered states at desktop
and mobile widths, and report any behavior that could not be verified.

Analyze the existing differences before extracting anything.

The line about ownership prevents the common mistake of mixing a visual extraction with a state-management rewrite.

Template: reducing duplication

Find the duplicated logic across [list of files] and propose the smallest
shared abstraction.

Behavior preservation: Preserve each caller's public behavior, default values,
error handling, telemetry, and timing.

Scope: Do not generalize outside these callers. Keep differences visible when
they represent product rules rather than accidental duplication.

Tests: Map each existing test to the shared behavior it protects. Add one test
for each meaningful divergence.

Acceptance criteria: Repeated logic is centralized only where the contract is
actually the same; callers remain readable and behaviorally equivalent.

Validation: Run the callers' focused tests and compare their observable output
before and after.

Return an analysis of common versus intentional differences before code.

Shared code is not automatically better. A prompt should make the assistant prove that the behavior is genuinely shared.

Template: performance refactoring

Investigate a performance problem in [screen/workflow].

Evidence: [measurement, trace, timing, user report, or reproducible scenario].
Do not assume [memoization/caching/code splitting] is the answer.

Behavior preservation: Keep user-visible loading, freshness, accessibility,
authorization, and error behavior unchanged.

Scope: Inspect [paths] first. Do not introduce persistent caching, a new state
library, or a server dependency without a measured need.

Tests: Keep existing behavior tests. Add a regression or measurement check only
if the project has a stable convention for it.

Acceptance criteria: Name the bottleneck, show a baseline and result, and keep
the protected behavior intact.

Validation: Run relevant tests, capture the agreed measurement, and document
tradeoffs such as freshness or memory.

This template makes the optimization evidence-driven instead of technique-driven.

Template: legacy-code refactoring

Refactor [legacy module] so that [specific risk or maintenance cost] is
reduced without changing its externally observed behavior.

Behavior preservation: List the legacy inputs, outputs, error modes, side
effects, file formats, and compatibility requirements that clients rely on.

Scope: Work inside [module/boundary]. Do not upgrade unrelated dependencies or
rewrite callers in the same change.

Tests: First characterize current behavior with tests or fixtures where coverage
is missing. Include known edge cases and malformed input.

Acceptance criteria: The new structure is easier to reason about, the
characterized behavior remains stable, and compatibility notes are explicit.

Validation: Run characterization tests, existing integration tests, type check,
and a representative manual or command-line scenario.

Explain unknown behavior and risk before proposing an implementation.

For legacy code, a test that captures awkward existing behavior can be more valuable than a cleaner-looking rewrite.

Template: large refactoring

Plan a staged refactor of [system] to achieve [target architecture].

Behavior preservation: Maintain [public APIs, data compatibility, permissions,
user workflows, deployment behavior, and rollback path].

Scope: Divide the work into independently testable milestones. Identify files
that should not change in the first milestone.

Tests: Define the focused tests, contract tests, migration checks, and manual
workflows each milestone must pass before the next begins.

Acceptance criteria: Each stage has a clear entry condition, observable result,
rollback strategy, and no hidden dependency on a later stage.

Validation: Review the plan against current architecture, run every stage's
checks, and stop if a milestone invalidates the original assumption.

Do not edit code until you present the stages, risks, and alternatives.

This is a planning prompt, not a request for one giant patch. It gives reviewers meaningful checkpoints.

Refactoring is still product work

Refactoring can break an interaction, lose an event, weaken an authorization decision, or translate a user-visible string incorrectly. Protect behavior as deliberately as you improve the code.

Use how to write better AI prompts for the core structure. For worked examples, read prompt engineering examples for software engineers. If a refactor starts because of a production incident, pair it with prompt templates for debugging production issues.

When a refactor changes a script, first verify the commands it preserves. Practice terminal workflows in the browser so validation is based on input and output, not memory.

References

These documentation links provide authoritative details for the commands used in this article.