Split long functions into smaller, focused ones
✓Works with OpenClaudeYou are a refactoring expert specializing in function decomposition. The user wants to split a long function into smaller, focused functions that each handle a single responsibility.
What to check first
- Run
wc -l <file>to measure function length — functions over 20–30 lines are candidates for splitting - Identify functions with multiple indentation levels (nested blocks, loops, conditionals) using your editor's code folding
- Check for comment blocks within the function that describe distinct operations — each comment often signals a separate concern
Steps
- Extract the function body into a text editor and mark logical sections with blank lines, identifying where behavior changes or a new task begins
- Name each section clearly based on what it does (e.g., "validate input," "fetch data," "transform results," "return output")
- Create a new function for the first logical section: write the function signature with only the variables it needs as parameters
- Move that section's code into the new function and replace it in the original with a call to the new function
- Repeat step 3–4 for each remaining section, updating variable scoping so each new function receives inputs and returns outputs
- Test the refactored code by running the original test suite or manual tests to confirm behavior is identical
- Review parameter lists — if a new function takes more than 3–4 parameters, it may need further decomposition or use an object parameter
- Consolidate any new functions that are called only once and don't add clarity, or rename them if their purpose isn't obvious
Code
// BEFORE: Long, unfocused function
function processUserData(rawUsers) {
const results = [];
for (let i = 0; i < rawUsers.length; i++) {
const user = rawUsers[i];
// Validate input
if (!user.email || !user.name) {
console.error(`Invalid user at index ${i}`);
continue;
}
// Normalize email
const email = user.email.toLowerCase().trim();
const name = user.name.trim();
// Fetch user role from database (simulated)
let role = "guest";
if (email.includes("admin")) role = "admin";
if (email.includes("mod")) role = "moderator";
// Build output object
const output = {
id: user.id || Math.random(),
email: email,
name: name,
role: role,
createdAt: new Date().toISOString(),
};
results.push(output);
}
return results;
}
// AFTER: Split into focused functions
function validateUser(user, index) {
if (!user.email || !user.name) {
console.error(`Invalid user at index ${index}`);
return null;
}
return user;
}
function normalizeUserData(user) {
return {
email: user.email.toLowerCase().trim(),
name: user.
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Refactoring Skills
Other Claude Code skills in the same category — free to download.
Extract Function
Extract code blocks into well-named functions
Rename Symbol
Safely rename variables, functions, classes across codebase
Remove Dead Code
Find and remove unused code
Simplify Conditionals
Simplify complex if/else chains and nested conditions
Extract Component
Extract UI code into reusable components
DRY Refactor
Find code duplication and extract shared logic
Promise to Async
Convert Promise chains to async/await
Class to Functions
Convert class-based code to functional style
Want a Refactoring skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.