Lesson 5
Stepping into Refactoring Code with PHP
Stepping into Refactoring Code

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.

Just as each line of code is as essential as a brick in a building, clumsy code may lead to 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 by rewriting a complex game score computation function. Let's look at it:

php
1class Game 2{ 3 public static function computeScore($player, $monsters) 4 { 5 $score = 0; 6 foreach ($monsters as $monster) { 7 if ($player->power > $monster) { 8 $score += $player->power - $monster; 9 } else { 10 $score -= $monster - $player->power; 11 } 12 } 13 return $score; 14 } 15}

This code uses an algorithm to adjust the score based on the player's and monsters' power. 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 method, scoreChange.
  • We'll rename the original method to computeGameScore.

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

php
1// New method to calculate score changes. 2class Game 3{ 4 private static function scoreChange($power, $monster) 5 { 6 return $power > $monster ? $power - $monster : $monster - $power; 7 } 8 9 // Refactored method to calculate the game score. 10 public static function computeGameScore($player, $monsters) 11 { 12 $score = 0; 13 foreach ($monsters as $monster) { 14 $score += self::scoreChange($player->power, $monster); 15 } 16 return $score; 17 } 18}

This refactoring has simplified the method 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.

php
1class Game 2{ 3 public static function monsterReaction($monsterType, $player) 4 { 5 if ($monsterType === "ghost") { 6 if ($player->power > 5) { 7 echo "The ghost flees in terror!"; 8 } else { 9 echo "The ghost grumbles and attacks!"; 10 } 11 } elseif ($monsterType === "goblin") { 12 if ($player->power > 3) { 13 echo "The goblin groans and retreats!"; 14 } else { 15 echo "The goblin hacks with its sword!"; 16 } 17 } 18 // more monster types... 19 } 20}

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:

php
1abstract class Monster 2{ 3 abstract public function reaction($player); 4} 5 6class Ghost extends Monster 7{ 8 public function reaction($player) 9 { 10 if ($player->power > 5) { 11 echo "The ghost flees in terror!\n"; 12 } else { 13 echo "The ghost grumbles and attacks!\n"; 14 } 15 } 16} 17 18class Goblin extends Monster 19{ 20 public function reaction($player) 21 { 22 if ($player->power > 3) { 23 echo "The goblin groans and retreats!\n"; 24 } else { 25 echo "The goblin hacks with its sword!\n"; 26 } 27 } 28} 29 30// Game class where List of Monsters is managed 31class Game 32{ 33 public static function main($args) 34 { 35 $player = new Player(4); // This is just an example instantiation. 36 $monsters = [new Ghost(), new Goblin(), new Ghost(), new Goblin()]; 37 38 foreach ($monsters as $monster) { 39 $monster->reaction($player); 40 } 41 } 42}

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.