DEV Community

Cover image for Refactoring 002 - Extract Method
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

2

Refactoring 002 - Extract Method

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)
    }
Enter fullscreen mode Exit fullscreen mode

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.
    }
}
Enter fullscreen mode Exit fullscreen mode

Type

[X] Automatic

Many IDEs support this safe refactoring

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay