Extract Method

Group a code fragment into a separate function.

“If you have to spend effort looking at a fragment of code and figuring out what it does, you should extract it into a function and name the function after the ‘what’.” – Martin Fowler

Turn a block of code into a function with a name that explains its purpose.

graph LR
    A[Code Block] -->|Refactoring| B[Function Call]

When to apply (Smells)

  • Long Method: The method is too long to understand.
  • Comments: You see a comment explaining a block of code (e.g., // print details).
  • Duplication: The same code logic appears in multiple places.

Motivation

  • Readability: A function name like calculateTotal() is easier to read than a loop with math.
  • Reuse: Smaller functions can be reused.
  • Independence: Isolated functions are easier to test and override.

Mechanics (Steps)

  1. Create a new function with a descriptive name.
  2. Copy the extracted code into the new function.
  3. Pass any variables the code needs as parameters.
  4. Replace the original code with a call to the new function.
  5. Test.

Explanation

Problem

You have a code fragment that can be grouped together.

Solution

Move this code to a separate new method and replace the old code with a call to the method.

Real world analogy

Instead of reading a recipe that says “Crack eggs, beat them, add salt, heat pan, pour eggs”, you just say “Make Scrambled Eggs”. You group the steps into a named “function”.

Pros and Cons

Pros Cons
  • Better readability
  • Performance overhead (negligible)
  • Less duplication
  • More functions to manage
  • Comparison

    • Inverse Refactoring: Inline Method.

    Code example

    Typescript

    Before

    After

    PHP

    Before

    After