Introduction

Hello, Explorer! Today is about refactoring. Consider it as 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:

C#
// Before refactoring
public double Calculate(double total, int quantity) {
    double price = total / quantity;
    double tax = price * 0.2;
    double totalPrice = price + tax;
    return totalPrice;
}

// After refactoring
public double CalculateTotalPrice(double total, int quantity) {
    double price = CalculatePrice(total, quantity);
    double tax = CalculateTax(price);
    return price + tax;
}

public double CalculatePrice(double total, int quantity) {
    return total / quantity;
}

public double CalculateTax(double 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
public string GreetUser(string username) {
    username = username.Trim().ToLowerInvariant(); // Prepare the username
    string message = "Hello, " + username + "!"; // Prepare the message
    return message; // Return the prepared message
}

// After refactoring
public string CleanUsername(string username) {
    return username.Trim().ToLowerInvariant(); // Returns a cleaned version of the username
}

public string GreetUser(string username) {
    username = CleanUsername(username); // Clean the username
    string message = "Hello, " + username + "!"; // Prepare and return the message
    return message;
}

Here, we moved the username preparation from GreetUser into its own function, CleanUsername. Nice and tidy!

Using Rename Method
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