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 Function, Rename Function, 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:

func Calculate(total float64, quantity int) float64 {
    price := total / float64(quantity)
    tax := price * 0.2
    totalPrice := price + tax
    return totalPrice
}
func CalculateTotalPrice(total float64, quantity int) float64 {
    price := CalculatePrice(total, quantity)
    tax := CalculateTax(price)
    return price + tax
}

func CalculatePrice(total float64, quantity int) float64 {
    return total / float64(quantity)
}

func CalculateTax(price float64) float64 {
    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 Function

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

func GreetUser(username string) string {
    username = strings.TrimSpace(strings.ToLower(username)) // Prepare the username
    message := "Hello, " + username + "!" // Prepare the message
    return message // Return the prepared message
}
func CleanUsername(username string) string {
    return strings.TrimSpace(strings.ToLower(username)) // Returns a cleaned version of the username
}

func GreetUser(username string) string {
    username = CleanUsername(username) // Clean the username
    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 Function

Clear function 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 function:

func Fx(x float64) float64 {
    return 3.14 * (x * x) // Calculates a value that is pi times the square of x
}
func CalculateCircleArea(radius float64) float64 {
    return 3.14 * (radius * radius) // 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