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.

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, emphasizing the use of TypeScript's type annotations to improve code clarity.
  • OOP in Refactoring: We've learned how to leverage Object-Oriented Programming principles to enhance our code's structure with the help of TypeScript's robust type system.
  • Code Decoupling and Modularization: Methods to make code easier to manage by minimizing dependencies, utilizing TypeScript's powerful module and type systems.

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:

function computeScore(player: { power: number }, monsters: number[]): number {
    let score: number = 0;
    for (let monster of monsters) {
        if (player.power > monster) {
            score += player.power - monster;
        } else {
            score -= player.power - monster;
        }
    }
    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, scoreChange.
  • We'll rename the original function to computeGameScore.

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

// New function to calculate score changes.
function scoreChange(power: number, monster: number): number {
    if (power > monster) {
        return power - monster;
    } else {
        return monster - power;
    }
}

// Refactored function to calculate the game score.
function computeGameScore(player: { power: number }, monsters: number[]): number {
    let score: number = 0;
    for (let monster of monsters) {
        score += scoreChange(player.power, monster);
    }
    return score;
}

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