← Writing

Planning a Legacy Java Refactor with AI — Clean Code Principles and Practical Prompts

On this page

When you show legacy code to an AI tool, start by asking “What behavior must we preserve, and what small change can we make first?” The order in which exceptions occur, the data left behind after a failure, and calls to external systems can all be part of the contract. Names and line counts rarely reveal that contract. A refactoring plan should document it and say how to verify the same behavior after each small change. Martin Fowler’s introduction to refactoring

Turn clean code principles into review criteria

Suppose OrderService.cancelOrder() looks up the order, checks whether cancellation is allowed, saves the new state, and publishes a notification. Splitting a service solely because a method is long would enlarge the change. Start with a concrete problem instead. The cancellation rules are hard to change.

Criterion What to ask the AI
Names that reveal intent What business rule does check() check? Would isCancellationAllowed() describe its role more precisely?
One responsibility Can you extract just the cancellation checks, with no database or external API calls?
Removing duplication Do two conditions happen to match today, or should they evolve together because they express the same rule?
Readable branches Can guard clauses preserve error precedence when more than one condition fails?

Suppose the API returns ALREADY_CANCELLED when the order has already been canceled and is also past its cancellation deadline. Moving the deadline check first could change the response. Add a test for the overlapping conditions before moving either check. Replace Nested Conditional with Guard Clauses · Java early return example

If an order is already canceled and past its deadline, checking cancellation status first returns ALREADY_CANCELLED. Checking the deadline first returns DEADLINE_EXCEEDED in this example.

Illustrative pseudocode. It shows only the two overlapping checks. DEADLINE_EXCEEDED is an example code for this scenario.

Existing check order
if alreadyCancelled: return ALREADY_CANCELLED
if deadlinePassed:    return DEADLINE_EXCEEDED

Deadline check first
if deadlinePassed:    return DEADLINE_EXCEEDED
if alreadyCancelled: return ALREADY_CANCELLED

Copyable prompt for planning the refactor

Gather one target method, its direct callers, and the relevant tests. If the method writes data or calls another system, include the code that shows where those operations take place. Remove secrets and customer data from test logs or incident examples before sharing them.

Write a refactoring plan in English for the legacy Java code below.

Goal
- [Example: Make the order cancellation rules easier to read and change.]
- Target: [file path and method name].
- Read the inputs and produce a plan only. Do not edit files or generate a patch.

Inputs
- Target code: [paste it or specify the repository path]
- Direct callers and relevant tests: [paths or code]
- Known business rules, incidents, and runtime environment: [what you know]
- Test command: [example: ./gradlew test --tests '*OrderServiceTest']

Analysis
1. List the behavior callers can observe today.
   Include inputs, return values, exceptions and error precedence, database
   changes, transaction boundaries, and the count and order of external calls
   and events. Cite files, methods, or tests for established facts.
   Distinguish behavior visible in code, behavior confirmed by running tests,
   and hypotheses that need checking.

2. Review names, responsibilities, duplication, and branches.
   Explain what each proposal makes easier to read or change.
   If similar conditions may represent different rules, list what to ask
   before combining them.

3. Pick one small change for the first PR.
   List tests that capture existing behavior before editing, with expected
   results for success, boundary values, overlapping failures, and save failure.
   Describe dependencies between later steps and order those steps so each can
   be verified and reverted independently.

Constraints
- Preserve public method signatures, API responses, error precedence,
  transaction boundaries, and the order of saves and events.
- Keep bug fixes, policy changes, and dependency replacements separate.
- Mark tests that were not run. If an expected result is unknown, state
  what evidence is missing.

Output
- Table of behavior to preserve
- First PR scope and test list
- Follow-up changes in order, with completion criteria for each
- Questions to answer before finalizing the plan

What the first PR looks like for order cancellation

The table shows an example of the plan to expect. The order service is fictional. The example comes from writing out the scenario, with no repository analysis or prompt run in an AI tool.

Step Work Completion criteria
1. Record existing behavior Prepare tests for successful cancellation, an already canceled order, the deadline boundary and a passed deadline, both failures together, and a save failure. Run them against the current code to confirm responses, error precedence, and whether saving and notification occur on failure paths.
2. Extract the cancellation checks Move only the cancellation eligibility checks into a named method. The existing tests pass. Call order, transaction behavior, and API responses stay the same.
3. Simplify branching if needed Apply guard clauses if the conditions are still hard to read. The overlapping failure still returns the same error.

Record the tests in step 1 before changing the method. The first refactoring PR takes the extraction in step 2. Keep the optional branch cleanup for a follow-up.

If the code provided leaves transaction boundaries or notification timing unclear, record what needs investigation. A mock can show when the save and publisher are called. Checking whether a save failure actually prevents an event from being delivered may also require an integration test that can observe the real transaction boundary. Extract Function

Review the first change before implementing it

A long AI-generated plan can blur the scope of the first PR. Use this prompt to find where behavior might change before editing any code.

Review only the first PR in the refactoring plan below.

[Paste the plan, target code, and relevant tests.]

Start with inputs for which the result might change.
Check the order of checks and calls, especially when two conditions fail
at once or when saving fails.
For each risk, give evidence from the existing code, the expected difference,
and one test that would catch it.
If evidence is missing, say which code or execution record you need.
Finish by naming changes that can stay outside the first PR.

Start implementation once you can describe the behavior the first PR preserves in tests. For calculation rules such as shipping fees, cover boundary values and combinations of inputs. For a state change such as order cancellation, also check saves and events. Java shipping fee refactoring exercise · Refactor and verify changes with an AI agent

Discussion

View on GitHub ↗