4

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 ?

3

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.

  • indeed, the goal is to move out code and reduce method size, good point. – Benj Jun 18 '16 at 18:04
  • 1
    @Benj Also, I can't quite articulate this, but I think immediately invoked methods read poorly and their non-standardness (imo, but I don't develop in your language) suggest there's some special circumstance when there in fact isn't. – Nathan Cooper Jun 18 '16 at 18:20
  • 1
    Also "Besides eliminating rough edges in your code, extracting methods is also a step in many other refactoring approaches". You can't e.g. extract a class if the related methods you could move out are buried somewhere, and potentially rely on closures. – kamilk Jun 18 '16 at 21:54
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.