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 Algorithmtechniques 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:
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:
This refactoring has simplified the function and made it easier to modify in the future.
