Welcome to our captivating session on refactoring, a powerful tool for tidying up code, much like organizing a messy toy box or finding 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.
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
, andSubstitute Algorithm
techniques in earlier lessons, emphasizing the use of TypeScript's type annotations to improve code clarity. - OOP in Refactoring: We've learned how to leverage Object-Oriented Programming principles to enhance our code's structure with the help of TypeScript's robust type system.
- Code Decoupling and Modularization: Methods to make code easier to manage by minimizing dependencies, utilizing TypeScript's powerful module and type systems.
We'll use these concepts as guiding stars as we traverse the cosmos of refactoring.
We'll start by rewriting a complex game score computation function. Let's look at it:
TypeScript1function computeScore(player: { power: number }, monsters: number[]): number { 2 let score: number = 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:
TypeScript1// New function to calculate score changes. 2function scoreChange(power: number, monster: number): number { 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: { power: number }, monsters: number[]): number { 12 let score: number = 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.
Let's consider another example where the game has multiple types of monsters. Each monster type behaves differently when encountered by a player.
TypeScript1function monsterReaction(monsterType: string, player: { power: number }): void { 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 methodreaction
that could be overridden by each type of monster. - Then, we'll create child classes
Ghost
andGoblin
that inherit fromMonster
and implement their ownreaction
methods.
Under the revised structure, our game code would look like this:
TypeScript1class Monster { 2 reaction(player: { power: number }): void { 3 throw new Error('This method should be overridden'); 4 } 5} 6 7class Ghost extends Monster { 8 reaction(player: { power: number }): void { 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: { power: number }): void { 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 27const monsters: Monster[] = [new Ghost(), new Goblin(), new Ghost(), new Goblin()]; 28const player = { power: 4 }; // Example player 29 30for (let monster of monsters) { 31 monster.reaction(player); 32}
Now, our code dealing with multiple monsters is easier to manage and can be extended to accommodate more types of monsters.
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 using TypeScript.
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!