Break down a complex, hard-to-read function into smaller, well-named, testable functions with clear responsibilities.
Fill in this template
The {{ }} placeholders are variables — drop in your own details, then copy the ready-to-use prompt. (Or copy the template as-is and let your AI assistant fill them in.)
Preview filled prompt
You are a software engineer focused on clean code and maintainability.
## Complex Function
```
{{CODE}}
```
## Function Name
{{FUNCTION_NAME}}
## Instructions
Refactor this function to improve readability, maintainability, and testability.
### Analysis Phase
First, analyze the function:
1. What is the function's primary responsibility?
2. How many distinct concerns does it handle?
3. What is the current cyclomatic complexity (estimate)?
4. What are the input/output contracts?
5. Are there any hidden side effects?
### Refactoring Strategy
Apply these techniques as appropriate:
1. **Extract Method**: Pull cohesive blocks into named functions
- Each function should do one thing
- Name functions after what they do, not how they do it
- Keep functions under 15 lines where practical
2. **Replace Conditionals**:
- Replace nested if/else with early returns (guard clauses)
- Replace complex boolean expressions with named predicates
- Consider strategy pattern for type-based branching
3. **Introduce Intermediate Variables**:
- Name the results of complex expressions
- Make the data flow explicit
4. **Reduce Parameters**:
- Group related parameters into objects
- Use builder pattern for many optional params
5. **Eliminate Mutation**:
- Prefer immutable transformations
- Use map/filter/reduce over imperative loops where clearer
## Output Format
1. **Complexity Analysis**: Metrics before and after
2. **Extracted Functions**: Each new function with its responsibility
3. **Refactored Main Function**: The simplified orchestrator
4. **Before/After Comparison**: Side-by-side readability comparison
5. **Test Suggestions**: What to test for each extracted functionTags
Explore more prompts and rules
BeforeMerge offers hundreds of AI prompts, code review rules, guides, and detection patterns to help your team ship better code.