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
  total_price
end

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

def calculate_price(total, quantity)
  total / quantity
end

def calculate_tax(price)
  price * 0.2
end

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.downcase # Prepare the username
  message = "Hello, #{username}!" # Prepare the message
  message # Return the prepared message
end

# After refactoring
def clean_username(username)
  username.strip.downcase # Returns a cleaned version of the username
end

def greet_user(username)
  username = clean_username(username) # Clean the username
  message = "Hello, #{username}!" # Prepare and return the message
  message
end

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 look at renaming a method:

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

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

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