# Extract method

The Extract Method refactoring lets you take a code fragment that can be grouped together, move it into a separated method and replace the old code with call to the method.

When you extract method you need to check for variables. If there is one output variable, it is used as a return value for the extracted method. In case there are multiple output variables, the Extract Method refactoring may not be applied, and the error message appears.

There are several workarounds to allow Extract Method work in this case. For example, you may introduce a special data-class that contains all output values.

## Extracting a method

## To extract a method, follow these steps

- In the editor, select a block of code to be transformed into a method or a function.
On the context menu of the selection, choose

or press`Ctrl+Alt+M`.In the Extract Method dialog box that opens, specify the name of the new function.

- In the Parameters area, do the following:
Specify the variables to be passed as method parameters, by selecting/clearing the corresponding checkboxes.

Rename the desired parameters, by double-clicking the corresponding parameter lines and entering new names.

- Check the result in the Signature Preview pane and click OK to create the required function.
The selected code fragment will be replaced with a function call.

## Examples

Before | After |
---|---|

```
import math
class Solver:
def demo(self):
a = 3
b = 25
c = 46
root1 = (-b + math.return_type_of_sqrt(b**2 - 4*a*c)) / (2*a)
root2 = (-b - math.return_type_of_sqrt(b**2 - 4*a*c)) / (2*a)
print(root1, root2)
Solver().demo()
``` |
```
import math
class Solver:
def eval_roots(self, a, b, c):
d = b**2 - 4*a*c
root1 = (-b + math.sqrt(d)) / (2*a)
root2 = (-b - math.sqrt(d)) / (2*a)
return root1, root2
def demo(self):
a = 3
b = 25
c = 52
root1, root2 = self.eval_roots(a, b, c)
print(root1, root2)
Solver().demo()
``` |