Welcome to the Old Code Kitchen
Old software is like a busy kitchen. The soup may taste great, but the counter is cluttered. Legacy code means old code that still runs every day. People rely on it to run their business. We want to tidy this room without spilling the soup.
To refactor means to clean code without changing what it does. The math must stay the same. The screen results must stay identical too. AI assistants can help wash the dishes fast. But we must give them exact rules first.
Meet Nora. Nora owns a bakery called Sweet Breads. Her shop uses an old program to print paper bills. It works, but the text is messy and hard to read. She wants to use AI to clean it up safely.
- Legacy code is working software from the past.
- Refactoring cleans the design without changing the output.
- AI follows our rules to keep math completely safe.
Tools and Rules for Safe Cleaning
Before you ask an AI for help, gather your tools. You need your existing source files. You also need sample data with known correct answers. A characterization check is a test that records how old code behaves right now.
Do not ask the tool to fix strange bugs yet. Keep bug fixes separate from pure cleaning work. You need a list of approved totals, file names, and dates. This list acts as your trusty tape measure.
You also need a mock setup for sending mail. A fake adapter is pretend code that acts like an email box. It stops real emails from flying out during your test runs. That keeps customers happy while you work.
How to Plan Your AI Tidy Steps
Start small. Pick one tiny room before you paint the whole house. Run your old program with standard test inputs. Write down the exact numbers it produces down to the penny.
Next, draw a clear line between two tasks. A pure calculation is math that does not touch files or printers. A side effect is an action like saving a file or sending mail. Keep these two jobs far apart.
Now invite the AI to help with just the math. Ask the AI to move formulas behind a clean door. An interface is a tidy doorway between two blocks of code. Check that the answers match your written notes.
- Record current inputs and results before making changes.
- Choose one small area of the file to tidy.
- Separate plain math steps from file and mail tasks.
- Run your safety checks before and after every step.
Nora and the Invoice Machine
Nora has one giant routine called PrintBill. It checks coupon discounts, computes local sales tax, creates a PDF, and sends emails. Everything sits in one big, scary pile of text.
Nora creates three test baskets with controlled practice data. The first basket is an ordinary loaf of sourdough for five dollars. The second basket has a ten percent holiday discount. The third basket is an empty cart with zero items.
She tells the AI to extract only the math rules. She forbids the AI from changing her odd rounding system. Old code might drop extra pennies in a special way. We must keep that rule exactly as it is.
- Test Case Alpha: One five-dollar loaf with five percent tax.
- Test Case Beta: Ten-dollar cake with a one-dollar discount coupon.
- Test Case Gamma: Zero-item basket to test error handling cleanly.
A Second Use Case: Gym Member Passes
Let us look at another real case. Sam runs a community gym. His system checks member card scans at the front turnstile. It calculates active days, verifies fee waivers, and unlocks the gate.
Sam wants AI to tidy this crowded gate script. First, he records three member badge records. He logs an active pass, an expired pass, and a family pass. He tests them on a fake turnstile first.
The AI pulls out the day-counting logic into a separate helper. It does not touch the gate motor code yet. Sam checks that badge math still matches the front desk logs. His members walk through without any delays.
Common Traps and Quick Fixes
AI agents love to fix typos and odd math. But that can cause hidden damage. If the AI changes how cents are rounded, prices will drift. Tell the AI that old business rules must never change.
Another risk is accidental double action. Idempotent behavior means running a job twice leaves things clean and unchanged. If an invoice runs twice, it should never charge a card twice.
Watch the order of steps closely. Never send a receipt email before saving the record to disk. If the server crashes in between, the customer gets confused. Use fake adapters so test emails never leave your laptop.
Compare Before and After
Now we compare our new code with our old notes. We want to see exact matches across every test run. If an invoice failed before, it must fail in the same safe way now.
Store your proof in a neat folder. Save the old printouts right next to the new ones. If you spotted an old bug, write it down on a separate notepad. Do not mix bug repair with clean-up work. Use this table to plan your own checks. Each row shows the result to look for in the practice case.
| Controlled Case | Expected Evidence |
|---|---|
| Discounted invoice runs again | Line items and final totals match old records. |
| File storage step fails | No email is sent and an error note appears. |
| Same billing request retried | Duplicate bill is blocked and state stays clean. |
A Fast Test You Can Run Right Now
You can try this safety test on your own computer today. Take a simple math script that adds tax to prices. Run three sample numbers through it and save the answers on paper.
Next, paste the script into your AI tool. Ask it to split the math into a neat helper function. Forbid it from altering numbers or introducing new software libraries.
Run your three sample numbers through the new version. Do the answers match your paper notes down to the penny? If yes, your first refactor succeeded. You have learned the safe way to tidy code.
Your Next Practical Move
Pick one small script in your project that needs some love. Write your test cases down before you open your editor. Keep your focus on small, calm steps that build confidence.
Roseram can help you organize and review these code tasks easily. Roseram access and limits depend on your current active plan. Set your boundaries clearly so your assistant stays on target. Clear tests keep any smart helper safe and helpful. Take your first small step today and enjoy clean code.
Refactor the PrintBill function for Nora's bakery. Split it into a pure calculation block and an orchestration block. Use these sample inputs: Test Alpha ($5 loaf, 5% tax), Test Beta ($10 cake, $1 discount), and Test Gamma (0 items). Do not alter existing rounding rules or tax calculations. Use a fake adapter for email delivery so no real messages are sent. Log any business rule bugs separately without changing them.
Your idea. Your next step.
Put Roseram super intelligence to work.
Bring the idea you keep coming back to. Choose a Roseram plan, then give your project a clear first task. You can think it through, build a first version, and improve it as you learn.
Check current access, plan limits, and pricing before joining.
Your next step
Your quick checklist.
Tick a step as you finish it. Your ticks and feedback stay on this device. They are not public reviews.
0 of 7 complete
Tell the community what you tried or tell us what needs fixing. Include a source if you are correcting a fact.
Your questions, answered
Can AI guess our true business rules from names?
No. AI can only guess. You must check every rule yourself.
Should we fix old bugs while we clean code?
No. Fix bugs in a separate step. This keeps your safety checks clear.
How do I know the task is done?
Old inputs must match new outputs. Keep core math away from side actions.
Why use a fake adapter during these tests?
An adapter stands in for real tools. It stops test emails from sending.
Want the technical details?Open the code notes, deeper checks, and common questions.
These notes go deeper. Use the parts that fit your project. Examples are for learning; they are not claims that we tested your app.
A worked example: where the task becomes difficult
A fictional invoicing tool has a long function mixing discounts, tax presentation, file generation and email delivery. The owner wants maintainable code without changing invoice amounts. Begin with controlled invoices covering ordinary, discounted and zero-line-item cases. Separate pure calculations from side effects. Do not let the agent infer accounting policy from variable names or replace an approved rounding rule with its preferred convention.
Decisions to make before implementation
Define observable compatibility: calculated totals, output fields, file names, error outcomes and when delivery occurs. Use characterization checks where existing behavior is the contract, while identifying suspected bugs separately. Move calculations behind a stable interface before changing callers. Keep database migrations and dependency upgrades outside the refactor unless a documented necessity makes them part of the work.
A practical sequence for the work
Use the sequence below as a task boundary, not as a claim that the example has been executed. Work with approved inputs and the project’s actual architecture. If a required integration or permission is unavailable, keep that stage visibly incomplete rather than generating a plausible substitute result.
- Create controlled examples of current successful and failed invoice generation.
- Extract a pure calculation boundary while retaining approved rounding behavior.
- Move file and delivery orchestration separately without changing their public contract.
- Compare outputs and side effects before and after each structural step.
A detailed brief you can adapt for your agent
Replace the illustrative context with your approved facts and controlled inputs. Keep the stated boundaries when adapting the brief. The expected deliverable matters more than a particular tool name: ask for an explanation grounded in the inspected material and evidence for the requested outcome.
Refactor invoice generation into calculation and orchestration boundaries without changing approved outputs. Use the supplied controlled invoice cases. Keep tax and rounding rules unchanged and isolate delivery through a fake adapter for tests. Report suspected business-rule bugs separately. Do not upgrade dependencies or migrate stored records as part of this structural task.
Failure modes that an attractive preview can hide
Legacy behavior can be wrong, but silently correcting it during a refactor makes comparisons ambiguous. Record the suspected defect as a product decision. Also watch for ordering changes: generating an invoice twice or sending it before persistence can cause real operational damage. Use fake delivery adapters during testing and explicitly preserve idempotent behavior where the workflow needs it.
Acceptance checks and the evidence to retain
Keep before/after output comparisons, the new responsibility map and any intentionally unchanged defects. Explain which checks establish compatibility and which cases remain unexamined.
| Controlled case | Expected evidence |
|---|---|
| Approved discounted invoice is recalculated | Line items and final amount remain compatible. |
| File generation fails | No unapproved delivery side effect occurs. |
| Same controlled request is retried | The documented duplicate-handling behavior is preserved. |
Common questions
Can AI infer the intended business rule?
It can form hypotheses; the owner must supply or verify rules whose correctness matters.
Should a refactor also fix every bug found?
Separate those decisions so structural compatibility and intentional behavior changes can be reviewed clearly.
What is the practical completion criterion?
Keep before/after output comparisons, the new responsibility map and any intentionally unchanged defects. Explain which checks establish compatibility and which cases remain unexamined.
Where the facts come from
Use these links to check the technical facts. The stories here are made-up examples to help you learn. Roseram sells AI tools; our examples are not promises of results.
- GitHub: getting useful results from coding tasks ↗
What this source covers
Provider-specific reference for clear task scope and repository instructions; the worked workflows here are original analysis, not claims that every agent implements GitHub features.
References last reviewed 2026-10-11. Writing refreshed 2026-10-14. Spot a mistake? Tell us.