Lesson 5
Refactoring in Action: Simplifying Complex Code for Beginners
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.

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.

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:

Python
1def compute_score(player, monsters): 2 score = 0 3 for monster in monsters: 4 if player.power > monster: 5 score += player.power - monster 6 else: 7 score -= player.power - monster 8 return score

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, score_change.
  • We'll rename the original function to compute_game_score.

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

Python
1# New function to calculate score changes. 2def score_change(power, monster): 3 if power > monster: 4 return power - monster 5 else: 6 return monster - power 7 8# Refactored function to calculate the game score. 9def compute_game_score(player, monsters): 10 score = 0 11 for monster in monsters: 12 score += score_change(player.power, monster) 13 return score

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.

Python
1def monster_reaction(monster_type, player): 2 if monster_type == 'ghost': 3 if player.power > 5: 4 print("The ghost flees in terror!") 5 else: 6 print("The ghost grumbles and attacks!") 7 elif monster_type == 'goblin': 8 if player.power > 3: 9 print("The goblin groans and retreats!") 10 else: 11 print("The goblin hacks with its sword!") 12 # more monster types...

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:

Python
1class Monster: 2 def reaction(self, player): 3 pass 4 5class Ghost(Monster): 6 def reaction(self, player): 7 if player.power > 5: 8 print("The ghost flees in terror!") 9 else: 10 print("The ghost grumbles and attacks!") 11 12class Goblin(Monster): 13 def reaction(self, player): 14 if player.power > 3: 15 print("The goblin groans and retreats!") 16 else: 17 print("The goblin hacks with its sword!") 18 19monsters = [Ghost(), Goblin(), Ghost(), Goblin()] 20for monster in monsters: 21 monster.reaction(player)

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.