# 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

- %[https://maximilianocontieri.com/code-smell-03-functions-are-too-long]

- %[https://maximilianocontieri.com/code-smell-05-comment-abusers]

- %[https://maximilianocontieri.com/code-smell-18-static-functions]

- %[https://maximilianocontieri.com/code-smell-22-helpers]

- %[https://maximilianocontieri.com/code-smell-74-empty-lines]

- %[https://maximilianocontieri.com/code-smell-78-callback-hell]

- %[https://maximilianocontieri.com/code-smell-102-arrow-code]

# 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

[Gist Url]: # (https://gist.github.com/mcsee/18f22cff14d588942fc87893bb73edeb)
```kotlin
object Ingenuity {
    fun moveFollowingPerseverance() {
        //take Off
        raiseTo(10 feet)
      
        //move forward to perseverance
        while (distanceToPerseverance() < 5 feet){
             moveForward()             
         }
        
        //land
        raiseTo(0 feet)
    }
```

## After

[Gist Url]: # (https://gist.github.com/mcsee/d1e6a299bbb104132e48ee19a45efa7e)
```kotlin
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](https://maximilianocontieri.com/laziness-i-meta-programming).

# Tags

- Complexity

- Readability

# Related Refactorings

-  Move method to a new class

# Credits

Image by <a href="https://pixabay.com/users/hreisho-2216364/">Hreisho</a> from <a href="https://pixabay.com/">Pixabay</a>

* * * 

This article is part of the Refactoring Series.
