Introduction

Hello, explorer! Today is about refactoring. Think of it as organizing your favorite tool chest. We're going to learn about Extract Method, Rename Method, and Substitute Algorithm refactorings in C++. Refactoring helps us tidy up our code, making it cleaner and more maintainable, all while preserving its functionality.

Refactoring Overview

Consider having a complicated blueprint. Refactoring changes it into a clearer drawing. Our code is rearranged to enhance readability and efficiency without altering its behavior. Let's examine a short code snippet before and after refactoring:

// Before refactoring
double calculate(double total, int quantity) {
    double price = total / quantity;
    double tax = price * 0.2;
    double totalPrice = price + tax;
    return totalPrice;
}
// After refactoring
double calculatePrice(double total, int quantity) {
    return total / quantity;
}

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

double calculateTotalPrice(double total, int quantity) {
    double price = calculatePrice(total, quantity);
    double tax = calculateTax(price);
    return price + tax;
}

Both code versions perform the same function, but the refactored version is simpler and easier to comprehend!

Understanding the Extract Method

Imagine a large set of instructions for setting up a desktop. The Extract Method technique is like having separate instructions for the monitor, CPU, keyboard, etc., instead of one large set of instructions. Observe this code:

// Before refactoring
std::string greetUser(std::string username) {
    // Prepare the username
    std::transform(username.begin(), username.end(), username.begin(), ::tolower);
    username.erase(username.find_last_not_of(" \n\r\t")+1); // Find the last non-whitespace character and erase everything after it
    std::string message = "Hello, " + username + "!"; // Prepare the message
    return message; // Return the prepared message
}
// After refactoring
std::string cleanUsername(std::string username) {
    // Returns a cleaned version of the username
    std::transform(username.begin(), username.end(), username.begin(), ::tolower);
    username.erase(username.find_last_not_of(" \n\r\t")+1); // Find the last non-whitespace character and erase everything after it
    return username;
}

std::string greetUser(std::string username) {
    username = cleanUsername(username); // Clean the username
    std::string message = "Hello, " + username + "!"; // Prepare and return the message
    return message;
}

Here, we moved the username preparation from greetUser into its dedicated function cleanUsername. Neat and organized!

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