I’m reading the ‘Refactoring’ book, and i’m at the “Extract method” technique:
Original code:
void printOwing() {
printBanner();
//print details
System.out.println ("name: " + _name);
System.out.println ("amount " + getOutstanding());
}
Refactored code with “Extract method” technique:
void printOwing() {
printBanner();
printDetails(getOutstanding());
}
void printDetails (double outstanding) {
System.out.println ("name: " + _name);
System.out.println ("amount " + outstanding);
}
What if instead I would write an immediately invoked function, which would have the benefit of clearly isolating and name labeling the part of code I would have extracted ? Within the IDE, I could collapse this method and have the benefit of clearly see the flow without extracted method in some other place:
void printOwing() {
printBanner();
void printDetails (double outstanding) { // collapsed in the ide
System.out.println ("name: " + _name);
System.out.println ("amount " + getOutstanding());
}() // self invokation
}
Isn’t this better than the “Extraction method” ? From your experience ?
What’s motivates method extraction here?
In this article with your exact example it says:
“The more lines found in a method, the harder it is to figure out what the method does. This is the main reason for this refactoring.”
As well as providing a meaningful name for a chunk of code, which your alternative solution also does, actually moving the code out of the original method keeps methods small and readable.
Edit: As it has been pointed out it makes it easier to extract into classes and reuse. It also eliminates complex sharing of variables via closures.
3
An additional benefit beyond naming a chunk of code through extraction is to make it available for reuse. An immediately invoked function cannot be called from a different context whereas a separate function/method can be made available to code elsewhere.