About 1 hour 15 mins:
To encourage quality code practices and being able to identify improvements that can be made to existing code.
Participants will be able to::
Read through lesson slides Refactoring
This is something people might not realize or might assume at first.
How would you refactor this?
const legs = function(numOfSpiders) {
let eyes = 2
let totalEyes = numOfSpiders * eyes
return numOfSpiders * 8
};
A possible solution:
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.
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.)
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
};
Ideas to help kickstart your refactoring:
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!
Can you find other pieces of code you wrote to refactor?