Refactor nested legacy loops into flat readable helper functions
Decompose deeply nested legacy loops into single-purpose functions. Use this when reviewing complex procedural code that is hard to test or debug.
You getA bulleted summary of logic changes, the complete refactored code with explanatory comments, and a short list of unit test cases to verify parity.
Prompt
Act as a software refactoring specialist. Refactor the pasted nested loop logic into clean, flat, and readable helper functions.
- Reduce nesting depth by using guard clauses, early returns, and dedicated single-responsibility helpers.
- Preserve the exact original business logic, variable names, and edge-case behavior without introducing external dependencies.
- State any hidden edge cases, side effects, or algorithmic complexity differences identified during the refactoring.
Output format: A bulleted summary of logic changes, the complete refactored code with explanatory comments, and a short list of unit test cases to verify parity.
Here is the legacy code to refactor:Example output
Paste your nested loops directly after the prompt in ChatGPT, Claude, or Gemini. As a follow-up, ask the model to generate Jest, Pytest, or Go test functions based on the proposed test cases.
Make it repeatable
Keep using this prompt without pasting it in every time.
Prompt details
- By
- Prompts-GPT editors
- Published
Did this prompt work?
Keep exploring
More like this
Plan an incremental refactor for legacy code
Break down monolith or fragile legacy modules into safe, testable milestones using branch-by-abstraction patterns.
Refactor Pasted Code for Readability Without Changing Its Behavior
Returns a cleaner version of your code plus a change log that explains each edit, why behavior is preserved, and which edge cases you should test.
Characterization Tests Before a Refactor
Writes tests that lock in a module's current behavior, including edge cases and quirks, so you can refactor safely.
Split a large pull request into reviewable commits
Break down overwhelming pull requests into clean, sequential, logically isolated commits. Use it when code reviews stall due to sprawling diffs.
Document module behavior from its test suite
Extract clear business rules, accepted inputs, and edge cases for undocumented modules solely from their test suites.
Trace an execution path from entry to database
Map out the complete end-to-end execution path of a single user request across layers in an unfamiliar codebase.
- Speed Up a Slow Function with Big-O Analysis and a Benchmark
- Port a Function or Module to Another Language With Tests Proving Same Behavior
- Unit Test Plan and Test Code for an Existing Function
- Convert raw error logs into a clean bug report
- Find the failing line in a stack trace
- Debug SQL query errors and incorrect row counts