Refactoring

Projected Time

About 1 hour 15 mins:

Prerequisites

Motivation

To encourage quality code practices and being able to identify improvements that can be made to existing code.

Objectives

Participants will be able to::

Materials

Lesson

Common Mistakes / Misconceptions

This is something people might not realize or might assume at first.

Guided Practice

How would you refactor this?

const legs = function(numOfSpiders) {
    let eyes = 2
    let totalEyes = numOfSpiders * eyes
    return numOfSpiders * 8
};

A possible solution:

  1. The number 8 is a “magic number” - let’s declare it as a constant (eg: let NUM_OF_SPIDER_LEGS = 8) Using all caps is a good way to indicate to someone else that this variable is a magic number.

  2. Make let legs more descriptive (eg: let getTotalNumOfSpiderLegs) This variable name makes it very clear that we are talking about both spider legs and trying to get the number. The variable name may be a bit long, but better to be long and clear, than short and confusing.)

  3. Remove any dead code since it isn’t used in the function (eg: let eyes & let totalEyes) It can be tempting to save code for “one day”. You might think “What if maybe one day I want to calculate the total number of spider eyes?”. It’s better to just add that code back once you actually use it, rather than leave confusing code and having someone else spend time trying to figure out why eyes is important to this function.

Your refactored code may look like this (but doesn’t have to!):

const getTotalNumOfSpiderLegs = function(numOfSpiders) {
    let NUM_OF_SPIDER_LEGS = 8;
  return numOfSpiders * NUM_OF_SPIDER_LEGS
};

Independent Practice

  1. Read this blog post on visualizing refactoring.
  2. Read about the different code smells to look for.
  3. Pick any exercise you completed early in the program. Find at least 2 places that your code can be refactored, and refactor it.

Ideas to help kickstart your refactoring:

Group Practice

Ask a partner to review your original code. Don’t tell them what 2 places you chose to refactor yet. Ask your partner to find at least 2 places that your code can be refactored. Have them refactor it. Compare the 2 places that your partner found with what you picked during your Independent Practice. Are they the same? Are they different? If they are different, try refactoring your own code based on your partner’s suggestion. What do you think? Do you think your original code has improved from both you and your partner’s refactoring efforts? Now do the same and review your partner’s code. Congratulations! Not only did you just learn to refactor, but you also just completed a code review!

Challenge

Can you find other pieces of code you wrote to refactor?

Supplemental Materials