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.
Let's briefly revisit a few key concepts using Go:
- Code Smells: Indicators that our code needs refactoring, akin to clutter calling for cleanup.
- Refactoring Techniques: We've familiarized ourselves with
Extract Function
,Rename Function
, andSubstitute Algorithm
techniques in earlier lessons. - Go's Structs and Interfaces: We leverage
structs
for data organization andinterfaces
for defining behaviors, enabling cleaner and more maintainable code. - Code Decoupling and Modularization: Techniques to organize code effectively, minimizing dependencies and coupling, making the code easier to manage.
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 in Go. Let's look at it:
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 Function
and Rename Function
techniques 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:
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.
This scenario could also benefit from refactoring using OOP and Code Decoupling:
- First, we'll introduce an interface
Monster
with a methodReaction
that can be implemented by each type of monster. - Then, we'll create struct types
Ghost
andGoblin
that implement theMonster
interface and provide their ownReaction
methods.
Under the revised structure, our game code would look like this:
Now, our code dealing with multiple monsters is easier to manage and can be extended to accommodate more types of monsters by simply creating new structs that implement the Monster
interface.
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!
