Lesson 5
Stepping into Refactoring Code
Stepping into Refactoring Code

Welcome to our captivating session on refactoring, a powerful tool for tidying up code, much like you would organize a messy toy box or find a faster route to school.

Each line of code is as essential as a brick in a building; clumsy code may result in an unstable structure. Today, we'll focus on enhancing the readability, maintainability, and performance of our code through refactoring.

Recapping Crucial Concepts

Let's briefly revisit a few key concepts:

  • Code Smells: Indicators that our code needs refactoring, akin to clutter calling for cleanup.
  • Refactoring Techniques: We've familiarized ourselves with Extract Method, Rename Method, and Substitute Algorithm techniques in earlier lessons.
  • OOP in Refactoring: We've learned how to leverage Object-Oriented Programming principles to enhance our code's structure.
  • Code Decoupling and Modularization: Methods to make code easier to manage by minimizing dependencies.

We'll use these concepts as guiding stars as we traverse the cosmos of refactoring.

Practice Problem 1: Taming a Complex Function

We'll start with rewriting a complex game score computation function. Let's look at it:

JavaScript
1function computeScore(player, monsters) { 2 let score = 0; 3 for (let monster of monsters) { 4 if (player.power > monster) { 5 score += player.power - monster; 6 } else { 7 score -= player.power - monster; 8 } 9 } 10 return score; 11}

The parts player.power > monster and player.power - monster recur in this function, indicating room for refactoring. We'll apply the Extract Method and Rename Method to untangle this:

  • We'll extract the scoring logic into a separate function, scoreChange.
  • We'll rename the original function to computeGameScore.

With these adjustments, our improved code might look something like this:

JavaScript
1// New function to calculate score changes. 2function scoreChange(power, monster) { 3 if (power > monster) { 4 return power - monster; 5 } else { 6 return monster - power; 7 } 8} 9 10// Refactored function to calculate the game score. 11function computeGameScore(player, monsters) { 12 let score = 0; 13 for (let monster of monsters) { 14 score += scoreChange(player.power, monster); 15 } 16 return score; 17}

This refactoring has simplified the function and made it easier to modify in the future.

Practice Problem 2: Refactoring with OOP and Code Decoupling

Let's consider another example where the game has multiple types of monsters. Each monster type behaves differently when encountered by a player.

JavaScript
1function monsterReaction(monsterType, player) { 2 if (monsterType === 'ghost') { 3 if (player.power > 5) { 4 console.log("The ghost flees in terror!"); 5 } else { 6 console.log("The ghost grumbles and attacks!"); 7 } 8 } else if (monsterType === 'goblin') { 9 if (player.power > 3) { 10 console.log("The goblin groans and retreats!"); 11 } else { 12 console.log("The goblin hacks with its sword!"); 13 } 14 } 15 // more monster types... 16}

This scenario could also benefit from refactoring using OOP and Code Decoupling:

  • First, we'll introduce a class Monster with a method reaction that could be overridden by each type of monster.
  • Then, we'll create child classes Ghost and Goblin that inherit from Monster and implement their own reaction methods.

Under the revised structure, our game code would look like this:

JavaScript
1class Monster { 2 reaction(player) { 3 throw new Error('This method should be overridden'); 4 } 5} 6 7class Ghost extends Monster { 8 reaction(player) { 9 if (player.power > 5) { 10 console.log("The ghost flees in terror!"); 11 } else { 12 console.log("The ghost grumbles and attacks!"); 13 } 14 } 15} 16 17class Goblin extends Monster { 18 reaction(player) { 19 if (player.power > 3) { 20 console.log("The goblin groans and retreats!"); 21 } else { 22 console.log("The goblin hacks with its sword!"); 23 } 24 } 25} 26 27let monsters = [new Ghost(), new Goblin(), new Ghost(), new Goblin()]; 28for (let monster of monsters) { 29 monster.reaction(player); 30}

Now, our code dealing with multiple monsters is easier to manage and can be extended to accommodate more types of monsters.

Wrapping Up and Looking Ahead

Phew! We've done an excellent job working through two practical problems, enhancing our refactoring skills, and learning how to identify code smells and apply refactoring techniques.

The more you practice, the better you'll become at spotting code that could benefit from refactoring. Brace yourself for more practice tasks, and remember, always keep your code lean and efficient!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.