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:
- What is the function's primary responsibility?
- How many distinct concerns does it handle?
- What is the current cyclomatic complexity (estimate)?
- What are the input/output contracts?
- Are there any hidden side effects?
Refactoring Strategy
Apply these techniques as appropriate:
-
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
-
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
-
Introduce Intermediate Variables:
- Name the results of complex expressions
- Make the data flow explicit
-
Reduce Parameters:
- Group related parameters into objects
- Use builder pattern for many optional params
-
Eliminate Mutation:
- Prefer immutable transformations
- Use map/filter/reduce over imperative loops where clearer
- Complexity Analysis: Metrics before and after
- Extracted Functions: Each new function with its responsibility
- Refactored Main Function: The simplified orchestrator
- Before/After Comparison: Side-by-side readability comparison
- Test Suggestions: What to test for each extracted function