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.
As 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. - 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.
We'll start by rewriting a complex game score computation function. Let's look at it:
Java1public class Game { 2 public static int computeScore(Player player, List<Integer> monsters) { 3 int score = 0; 4 for (int monster : monsters) { 5 if (player.getPower() > monster) { 6 score += player.getPower() - monster; 7 } else { 8 score -= player.getPower() - monster; 9 } 10 } 11 return score; 12 } 13}
This code uses some algorithm to adjust the score based on the player's and monster's power. The parts player.getPower() > monster
and player.getPower() - 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:
Java1// New function to calculate score changes. 2public class Game { 3 private static int scoreChange(int power, int monster) { 4 if (power > monster) { 5 return power - monster; 6 } else { 7 return monster - power; 8 } 9 } 10 11 // Refactored function to calculate the game score. 12 public static int computeGameScore(Player player, List<Integer> monsters) { 13 int score = 0; 14 for (int monster : monsters) { 15 score += scoreChange(player.getPower(), monster); 16 } 17 return score; 18 } 19}
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.
Java1public class Game { 2 public static void monsterReaction(String monsterType, Player player) { 3 if (monsterType.equals("ghost")) { 4 if (player.getPower() > 5) { 5 System.out.println("The ghost flees in terror!"); 6 } else { 7 System.out.println("The ghost grumbles and attacks!"); 8 } 9 } else if (monsterType.equals("goblin")) { 10 if (player.getPower() > 3) { 11 System.out.println("The goblin groans and retreats!"); 12 } else { 13 System.out.println("The goblin hacks with its sword!"); 14 } 15 } 16 // more monster types... 17 } 18}
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:
Java1public abstract class Monster { 2 public abstract void reaction(Player player); 3} 4 5public class Ghost extends Monster { 6 @Override 7 public void reaction(Player player) { 8 if (player.getPower() > 5) { 9 System.out.println("The ghost flees in terror!"); 10 } else { 11 System.out.println("The ghost grumbles and attacks!"); 12 } 13 } 14} 15 16public class Goblin extends Monster { 17 @Override 18 public void reaction(Player player) { 19 if (player.getPower() > 3) { 20 System.out.println("The goblin groans and retreats!"); 21 } else { 22 System.out.println("The goblin hacks with its sword!"); 23 } 24 } 25} 26 27// Game class where List of Monsters is managed 28public class Game { 29 public static void main(String[] args) { 30 Player player = new Player(4); // This is just an example instantiation. 31 List<Monster> monsters = Arrays.asList(new Ghost(), new Goblin(), new Ghost(), new Goblin()); 32 for (Monster monster : monsters) { 33 monster.reaction(player); 34 } 35 } 36}
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.
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!