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:

# Before refactoring
def calculate(total, quantity):
    price = total / quantity
    tax = price * 0.2
    total_price = price + tax
    return total_price

# After refactoring
def calculate_total_price(total, quantity):
    price = calculate_price(total, quantity)
    tax = calculate_tax(price)
    return price + tax

def calculate_price(total, quantity):
    return total / quantity

def calculate_tax(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
def greet_user(username):
    username = username.strip().lower() # Prepare the username
    message = f'Hello, {username}!' # Prepare the message
    return message # Return the prepared message

# After refactoring
def clean_username(username):
    return username.strip().lower() # Returns a cleaned version of the username

def greet_user(username):
    username = clean_username(username) # Clean the username
    message = f'Hello, {username}!' # Prepare and return the message
    return message

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

Using Rename Method

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

# Before refactoring
def fx(x):
    return 3.14 * (x ** 2) # Calculates a value that is pi times the square of x

# After refactoring
def calculate_circle_area(radius):
    return 3.14 * (radius ** 2) # Calculates the area of a circle with a given radius

Renaming the function fx to calculate_circle_area 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