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.

Exercise
Answer
Exercise

Extract the code in the connection.on method inside the constructor into a method called updateColor

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"

  • Name the method "updateColor"

  • 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.