Refactoring 002 - Extract Method

Refactoring 002 - Extract Method

Maxi Contieri

Published on Nov 25, 2021

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Table of contents

  • Problems Addressed
  • Related Code Smells
  • Steps
  • Sample Code
  • Type
  • Why code is better?
  • Limitations
  • Tags
  • Related Refactorings
  • Credits

Find some code snippets that can be grouped and called atomically.

TL;DR: Group your cohesive sentences together

Problems Addressed

  • Readability

  • Complexity

  • Code Reuse

Related Code Smells

Steps

  1. Move the code fragment to a separate new method

  2. Replace the old code with a call to the recently created method.

Sample Code

Before

object Ingenuity {
    fun moveFollowingPerseverance() {
        //take Off
        raiseTo(10 feet)

        //move forward to perseverance
        while (distanceToPerseverance() < 5 feet){
             moveForward()             
         }

        //land
        raiseTo(0 feet)
    }

After

object Ingenuity {   
    //1. Move the code fragment to a separate new method 
    private fun takeOff() {
        raiseTo(10 feet)
    }

    //1. Move the code fragment to a separate new method 
    private fun moveForwardToPerseverance() {
       while (distanceToPerseverance() < 5 feet){
             moveForward()             
         }
    }

    //1. Move the code fragment to a separate new method 
    private fun land() {
        raiseTo(0 feet)
    }

    fun moveFollowingPerseverance() {
        takeOff()
        //2. Replace the old code with a call to the recently created method.
        moveForwardToPerseverance()
        //2. Replace the old code with a call to the recently created method.
        land()
        //2. Replace the old code with a call to the recently created method.
    }
}

Type

[X] Automatic

Many IDEs support this safe refactoring

Why code is better?

Code is more compact and easier to read.

Functions can be reused.

Algorithms and functions are more declarative hiding implementative details on extracted code.

Limitations

Does not work well if you use meta-programming anti-pattern.

Tags

  • Complexity

  • Readability

Related Refactorings

  • Move method to a new class

Credits

Image by Hreisho from Pixabay


This article is part of the Refactoring Series.

 
Share this