Long methods offer the perfect hiding place for unwanted duplicate code.
🚨 Problems
The more lines found in a method, the harder it’s to figure out what the method does. This is the main reason for this refactoring.
A method contains too many lines of code. Generally, any method longer than 20
lines should make you start asking questions.
Since it’s easier to write code than to read it, this “smell” remains unnoticed until the method turns into an ugly, oversized beast.
function printOwing(invoice) {
printBanner();
let outstannding = calculateOutstanding();
// print details
console.log(`name: ${invoice.customer}`)
console.log(`amount: ${outstanding}`)
}
âś… Solution
Extract Function:
- Create a new function, and name it after the intent of the function (name it by what it does, not by how it does it)
- Copy the extracted code from the source function into the new target function.
- Scan the extracted code for references to any variables that are local in scope to the source function and will not be in scope for the extracted function. Pass them as parameters.
- Compile after all variables are dealt with.
- Replace the extracted code in the source function with a call to the target function.
- Test.
function printOwing(invoice) {
printBanner();
let outstannding = calculateOutstanding();
printDetails(outstanding);
function printDetails(outstanding) {
console.log(`name: ${invoice.customer}`)
console.log(`amount: ${outstanding}`)
}
}
💪🏽 Benefits
- Improving code readability.
- Improving code maintainability.
- Improving code testability.
- Improving code reusability.
- Improving optimization in some cases. (Optimizing compilers often work better with shorter functions which can be cached more easily.)