Why this category matters Link to heading
The Refactor code category is the largest section in the cookbook, with 11 scenarios across multiple languages and architectural scales.
This category is not about cosmetic rewrites. It is about reducing complexity, risk, and maintenance cost.
Use cases Link to heading
- Developers modernizing legacy code safely
- Reviewers evaluating refactors for behavior parity
- Developers building a disciplined approach to refactor prompting
The 11 examples in this category Link to heading
- Improving code readability and maintainability
- Fixing lint errors
- Refactoring for performance optimization
- Refactoring for environmental sustainability
- Refactoring to implement a design pattern
- Refactoring data access layers
- Decoupling business logic from UI components
- Handling cross-cutting concerns
- Simplifying complex inheritance hierarchies
- Fixing database deadlocks or data integrity issues
- Translating code to a different programming language
Diagram: Refactor decision map Link to heading
Readability and maintainability refactors Link to heading
The cookbook shows four concrete readability techniques:
- Improve variable and parameter names.
- Replace long if/else chains with cleaner mappings.
- Reduce nested conditional logic with guard clauses.
- Split large methods into smaller single-purpose functions.
Representative prompt patterns:
Improve the variable names in this function.
Simplify this code. Avoid using if/else chains but retain all function return values.
Rewrite this code to avoid the nested if/else statements.
How could this method be refactored to be easier to maintain?
Lint-driven refactoring Link to heading
Target prompts toward:
- General lint cleanup.
- Style guide-specific rules (for example PEP8).
- Attached custom style guide files.
- Single lint rule classes.
Key safety note:
- Re-run your linter after applying suggestions because generated changes may not resolve every issue.
Performance and sustainability refactoring Link to heading
Performance focus:
- Replace naive prime-number generation with a more efficient sieve approach.
Sustainability focus:
- Reduce memory usage and compute overhead (for example line counting using streaming iteration and built-ins).
Prompt patterns:
Optimize this code for performance.
Refactor this code to improve environmental sustainability by reducing memory usage and computational overhead.
Design and architecture refactoring Link to heading
Refactor with design patterns Link to heading
Recommended flow:
- Ask for candidate patterns first (no code).
- Ask to implement selected pattern.
Example flow:
What design patterns could improve this code? Do not show code examples.
Refactor this code using the module pattern.
Refactor data access layers Link to heading
Recommended flow:
- Ask for improvements list first.
- Ask for rewritten modular architecture.
Prioritize these improvements:
- Repository pattern
- Context manager for connection lifecycle
- Parameterized queries for SQL injection prevention
- Error handling and modular separation
Decouple business logic from UI Link to heading
Typical move:
- Move state/business logic from a React component into Redux structure.
Handle cross-cutting concerns Link to heading
Typical move:
- Centralize logging through AOP/decorator-style approaches.
- In VS Code, @workspace can provide cross-file context for this transformation.
Simplify inheritance hierarchies Link to heading
Typical move:
- Flatten deep inheritance where only shared base properties are required.
Database deadlock and integrity refactoring Link to heading
The cookbook includes advanced SQL transaction guidance:
- Keep transactions short.
- Access rows in consistent order.
- Add indexing for query predicates.
- Batch large operations.
- Use transaction-safe error handling for integrity.
Representative prompts:
How can I rewrite this transaction to reduce deadlock risk while preserving performance?
How can I ensure these operations are only performed if both succeed?
Code translation refactoring Link to heading
The cookbook includes a Perl-to-TypeScript translation example with strict behavior parity requirements.
Prompt pattern:
Tell me how I can convert this Perl script to TypeScript.
The functionality and output should be exactly the same.
Also tell me how to run it using Node.
Important guardrail:
- Validate parity with tests or snapshot outputs before replacing production code.
When to avoid big-bang refactors Link to heading
- Avoid broad rewrites when behavior is poorly understood or undocumented.
- Avoid multi-concern refactors in one patch (for example, readability plus architecture plus performance).
- Avoid merging large refactors without parity tests and rollback paths.
- Prefer sequenced, reviewable changes with measurable outcomes at each step.
A practical review checklist for all refactors Link to heading
- Behavioral parity: outputs and side effects match requirements.
- Complexity: code is actually simpler, not just reorganized.
- Test impact: existing tests still pass and new edge cases are covered.
- Security: no unsafe shortcuts introduced.
- Performance: claims are measured, not assumed.
Worked example Link to heading
Scenario Link to heading
A function has nested conditionals, duplicated parsing logic, and poor names.
def p(o):
r = []
for i in o:
if i["t"] == "A":
if i["q"] > 0:
if i["p"] > 0:
r.append(i["q"] * i["p"])
else:
r.append(0)
else:
r.append(0)
elif i["t"] == "B":
if i["q"] > 0:
r.append(i["q"] * i["p"] * 0.9)
else:
r.append(0)
return sum(r)
Problems: single-letter names (p, o, r, i), deep nesting, duplicated zero-appending, and implicit type "A"/"B" values with no named constants.
Prompt 1 (analysis first) Link to heading
Analyze this function for readability and maintainability problems.
Do not rewrite yet.
Return:
- top 5 issues
- minimal refactor plan
- behavior risks
Prompt 2 (targeted rewrite) Link to heading
Apply only the approved minimal refactor plan.
Preserve behavior exactly.
Return a patch-style response and list tests needed for parity.
Prompt 3 (parity checks) Link to heading
Given old and new versions, list edge-case inputs that could reveal behavior drift.
Validation steps Link to heading
- Run existing tests.
- Add the new edge-case tests suggested in prompt 3.
- Compare representative input/output snapshots.
This workflow keeps refactors controlled and reviewable.
Key takeaways Link to heading
- Refactoring prompts are strongest when they name a concrete smell and desired outcome.
- A two-step prompt flow (analyze first, rewrite second) improves architectural quality.
- Large transformations must include behavior parity and regression validation.
- Database and security-sensitive refactors need explicit operational constraints.
References Link to heading
- https://docs.github.com/en/copilot/tutorials/copilot-chat-cookbook
- https://docs.github.com/en/copilot/tutorials/copilot-chat-cookbook/refactor-code
- https://docs.github.com/en/copilot/tutorials/copilot-chat-cookbook/refactor-code/improve-code-readability
- https://docs.github.com/en/copilot/tutorials/copilot-chat-cookbook/refactor-code/fix-lint-errors
- https://docs.github.com/en/copilot/tutorials/copilot-chat-cookbook/refactor-code/refactor-for-optimization
- https://docs.github.com/en/copilot/tutorials/copilot-chat-cookbook/refactor-code/refactor-for-sustainability
- https://docs.github.com/en/copilot/tutorials/copilot-chat-cookbook/refactor-code/refactor-design-patterns
- https://docs.github.com/en/copilot/tutorials/copilot-chat-cookbook/refactor-code/refactor-data-access-layers
- https://docs.github.com/en/copilot/tutorials/copilot-chat-cookbook/refactor-code/decouple-business-logic
- https://docs.github.com/en/copilot/tutorials/copilot-chat-cookbook/refactor-code/handle-cross-cutting
- https://docs.github.com/en/copilot/tutorials/copilot-chat-cookbook/refactor-code/simplify-inheritance-hierarchies
- https://docs.github.com/en/copilot/tutorials/copilot-chat-cookbook/refactor-code/fix-database-deadlocks
- https://docs.github.com/en/copilot/tutorials/copilot-chat-cookbook/refactor-code/translate-code
- https://docs.github.com/en/copilot/tutorials/using-copilot-to-migrate-a-project