extract-method
Pull a code fragment into a named method to improve readability and enable reuse.
SKILL.mdskills/code-quality/extract-method/SKILL.md
GitHubExtract Method
A fragment of code can be grouped together, turned into its own method, and replaced with a call to that method.
When to Use
- Code fragment can be understood at a glance via a good name
- Method is too long (> 10–15 lines)
- Same fragment appears in multiple places (duplication)
- A comment explains what a block does — the comment should become the method name
How to Apply
- Create a new method; name it after the fragment's intent (not mechanics)
- Copy the fragment into the new method
- Identify local variables used in the fragment; pass them as parameters
- If a variable is modified, return it (or use an object)
- Replace the original fragment with a call to the new method
- Run tests
Example
// Before
function printOrder(order: Order) {
console.log(`Order #${order.id}`);
// print items
let total = 0;
for (const item of order.items) {
console.log(` ${item.name} x${item.qty} = ${item.price * item.qty}`);
total += item.price * item.qty;
}
console.log(`Total: ${total}`);
}
// After
function printOrder(order: Order) {
console.log(`Order #${order.id}`);
printItems(order.items);
}
function printItems(items: Item[]) {
let total = 0;
for (const item of items) {
console.log(` ${item.name} x${item.qty} = ${item.price * item.qty}`);
total += item.price * item.qty;
}
console.log(`Total: ${total}`);
}