Introduction

Hello, explorer! Today is about refactoring. Consider it like organizing your favorite toys in the toybox. We're going to learn about the Extract Method, Rename Method, and Substitute Algorithm refactorings. Refactoring helps us make our code cleaner and neater while keeping the functionality the same!

Refactoring Overview

Imagine having a complex map. Refactoring transforms it into simpler directions. Our code gets rearranged to make it more readable and efficient without altering what it does. Let's consider a small code snippet before and after refactoring:

// Before refactoring
function calculate(total, quantity) {
    let price = total / quantity;
    let tax = price * 0.2;
    return price + tax;
}

// After refactoring
function calculateTotalPrice(total, quantity) {
    let price = calculatePrice(total, quantity);
    let tax = calculateTax(price);
    return price + tax;
}

function calculatePrice(total, quantity) {
    return total / quantity;
}

function calculateTax(price) {
    return price * 0.2;
}

Both versions of the code do the same thing, but the latter is simpler and easier to understand!

Understanding the Extract Method

Imagine a large recipe for a complete breakfast. The Extract Method technique is like having separate recipes for eggs, toast, coffee, etc., instead of one large recipe. Take a look at this code:

// Before refactoring
function greetUser(username) {
    username = username.trim().toLowerCase(); // Prepare the username
    let message = `Hello, ${username}`; // Prepare the message
    return message; // Return the prepared message
}

// After refactoring
function cleanUsername(username) {
    return username.trim().toLowerCase(); // Returns a cleaned version of the username
}

function greetUser(username) {
    username = cleanUsername(username); // Clean the username
    let message = `Hello, ${username}`; // Prepare and return the message
    return message;
}

Here, we moved the username preparation from greetUser into its function cleanUsername. Nice and tidy!

Using Rename Method

Clear method names make it easy to understand our code, just as straightforward street names make navigating a city easier. Let's have a look at renaming a method:

// Before refactoring
function fx(x) {
    return 3.14 * (x ** 2); // Calculates a value that is pi times the square of x
}

// After refactoring
function calculateCircleArea(radius) {
    return 3.14 * (radius ** 2); // Calculates the area of a circle with a given radius
}

Renaming the function fx to calculateCircleArea makes it easier to understand its purpose.

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