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:

public class Game
{
    public static int ComputeScore(Player player, List<int> monsters)
    {
        int score = 0;
        foreach (int monster in monsters)
        {
            if (player.Power > monster)
            {
                score += player.Power - monster;
            }
            else
            {
                score -= player.Power - monster;
            }
        }
        return score;
    }
}

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:

// New method to calculate score changes.
public class Game
{
    private static int ScoreChange(int power, int monster)
    {
        return power > monster ? power - monster : monster - power;
    }

    // Refactored method to calculate the game score.
    public static int ComputeGameScore(Player player, List<int> monsters)
    {
        int score = 0;
        foreach (int monster in monsters)
        {
            score += ScoreChange(player.Power, monster);
        }
        return score;
    }
}

This refactoring has simplified the method and made it easier to modify in the future.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal