# Extract refactor

It's common to realize that a certain block of code is going to be used in multiple places. When you realize that, you usually want to extract this code into it's own method. VS Code includes an "Extract Method" refactoring tool to make this easier.

{% tabs %}
{% tab title="Exercise" %}
Extract the code in the `connection.on` method inside the constructor into a method called `updateColor`
{% endtab %}

{% tab title="Answer" %}

* Open the "app.js" file
* Highlight the code inside of the `connection.on` AFTER the "// update the bulb color" comment. Do not include the comment line.

```
// receives the "colorChanged" web socket event
connection.on("colorChanged", hex => {
  // update the bulb color
  bulb.style = `fill: #${hex};`;
  currentColor.textContent = `#${hex}`
});
```

* Press **Cmd/Ctrl + .**
* Select "Extract method in class "Application"

![](https://707761804-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LlvtEHKkq5bvzPq1pJ4%2F-LlvtJMfPaOZK9HU1qdu%2F-Lm0uA8TN7FMPx5Xslw4%2Fimage.png?alt=media\&token=75dbcdae-1301-4bb1-849e-89abbce27e11)

* Name the method "updateColor"

![](https://707761804-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LlvtEHKkq5bvzPq1pJ4%2F-LlvtJMfPaOZK9HU1qdu%2F-Lm0uK7xreyv857734-t%2Fimage.png?alt=media\&token=941a94b4-b686-47d6-b942-ddec07c807c8)

* Press **Enter**
* Notice that the code has been extracted to a new method in the `Application` class called `updateColor`. Also notice that the variable `hex` was automatically included as a parameter.

![](https://707761804-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LlvtEHKkq5bvzPq1pJ4%2F-LlvtJMfPaOZK9HU1qdu%2F-Lm0uw0qBPcXb5u2ZpzI%2Fimage.png?alt=media\&token=2406aa59-8a64-4ec3-bb79-efb8cbfecc84)
{% endtab %}
{% endtabs %}
