Introduction

Welcome to your next step in mastering Clean Code! 🚀 Previously, we emphasized the significance of naming conventions in clean coding. Now, we delve into the realm of functions, which serve as the backbone of application logic and are crucial for code organization and execution. Structuring these functions effectively is vital for enhancing the clarity and maintainability of a codebase. In this lesson, we'll explore best practices and techniques to ensure our code remains clean, efficient, and readable.

Clean Functions at a Glance

Let's outline the key principles for writing clean functions:

  • Keep functions small. Small functions are easier to read, comprehend, and maintain.
  • Focus on a single task. A function dedicated to one task is more reliable and simpler to debug.
  • Limit arguments to three or fewer. Excessive arguments complicate the function signature and make it difficult to understand and use.
  • Avoid boolean flags. Boolean flags can obscure the code's purpose; consider separate methods for different behaviors.
  • Eliminate side effects. Functions should avoid altering the external state or depending on external changes to ensure predictability.
  • Implement the DRY principle. Employ helper functions to reuse code, minimizing redundancy and enhancing maintainability.

Now, let's take a closer look at each of these rules.

Keep Functions Small

Functions should remain small, and if they become too large, consider splitting them into multiple, focused functions. While there's no fixed rule on what counts as large, a common guideline is around 15 to 25 lines of code, often defined by team conventions.

Below, you can see the processOrder function, which is manageable but has the potential to become unwieldy over time:

func processOrder(order Order, inventory Inventory, logger Logger) {
    // Step 1: Validate the order
    if !order.isValid() {
        logger.log("Invalid Order")
        return
    }

    // Step 2: Process payment
    if !order.processPayment() {
        logger.log("Payment failed")
        return
    }

    // Step 3: Update inventory
    inventory.update(order.items)

    // Step 4: Notify customer
    order.notifyCustomer()

    // Step 5: Log order processing
    logger.log("Order processed successfully")
}

Given that this process involves multiple steps, it can be improved by extracting each step into a dedicated function, as shown below:

func processOrder(order Order, inventory Inventory, logger Logger) {
    if !validateOrder(order, logger) || !processPayment(order, logger) {
        return
    }
    updateInventory(order, inventory)
    notifyCustomer(order)
    logOrderProcessing(logger)
}

// Step 1: Validate the order
func validateOrder(order Order, logger Logger) bool {
    if !order.isValid() {
        logger.log("Invalid Order")
        return false
    }
    return true
}

// Step 2: Process payment
func processPayment(order Order, logger Logger) bool {
    if !order.processPayment() {
        logger.log("Payment failed")
        return false
    }
    return true
}

// Step 3: Update inventory
func updateInventory(order Order, inventory Inventory) {
    inventory.update(order.items)
}

// Step 4: Notify customer
func notifyCustomer(order Order) {
    order.notifyCustomer()
}

// Step 5: Log order processing
func logOrderProcessing(logger Logger) {
    logger.log("Order processed successfully")
}
Single Responsibility

A function should embody the principle of doing one thing only. If a function handles multiple responsibilities, it may include several logical sections. Below, you can see the saveAndNotifyUser function, which is both too lengthy and does multiple different things at once:

func saveAndNotifyUser(user User, dataSource DataSource, webClient WebClient) {
    // Save user to the database
    if err := saveUser(user, dataSource); err != nil {
        fmt.Println(err)
        return
    }

    // Send a welcome email to the user
    if err := notifyUser(user, webClient); err != nil {
        fmt.Println(err)
    }
}

To enhance this code, you can create two dedicated functions for saving the user and sending the welcome email. This results in dedicated responsibilities for each function and clearer coordination:

// Save user to the database
func saveUser(user User, dataSource DataSource) error {
    stmt := "INSERT INTO users (name, email) VALUES (?, ?)"
    conn, err := dataSource.getConnection()
    if err != nil {
        return err
    }
    defer conn.close()

    _, err = conn.execute(stmt, user.name, user.email)
    if err != nil {
        return err
    }
    return nil
}

// Send a welcome email to the user
func notifyUser(user User, webClient WebClient) error {
    response, err := webClient.post("/sendWelcomeEmail", user)
    if err != nil {
        return err
    }

    if response.isError() {
        return fmt.Errorf("Failed to send email")
    }
    return nil
}
Limit Number of Arguments

Try to keep the number of function arguments to a maximum of three, as having too many can make functions less understandable and harder to use effectively. 🤔

Consider the saveAddress function below with five arguments, which makes the function less clean:

func saveAddress(street, city, state, zipCode, country string) {
    // Logic to save address
}

A cleaner version encapsulates the details into an Address struct type, reducing the number of arguments and making the function signature clearer:

type Address struct {
    Street, City, State, ZipCode, Country string
}

func saveAddress(address Address) {
    // Logic to save address
}
Avoid Boolean Flags

Boolean flags in functions can create confusion, as they often suggest multiple pathways or behaviors within a single function. Instead, use separate methods for distinct behaviors. 🚫

The setFlag function below uses a boolean flag to indicate user status, leading to potential complexity:

func setFlag(user User, isAdmin bool) {
    // Logic based on flag
}

A cleaner approach is to have distinct methods representing the different behaviors:

func grantAdminPrivileges(user User) {
    // Logic for admin rights
}

func revokeAdminPrivileges(user User) {
    // Logic to remove admin rights
}
Avoid Side Effects

A side effect occurs when a function modifies some state outside its scope or relies on something external. This can lead to unpredictable behavior and reduce code reliability.

Below, the addToTotal function demonstrates a side effect by modifying an external state:

// Not Clean - Side Effect
func addToTotal(value int) int {
    total += value // modifies external state
    return total
}

A cleaner version, calculateTotal, performs the operation without altering any external state:

// Clean - No Side Effect 🌟
func calculateTotal(initial, value int) int {
    return initial + value
}
Don't Repeat Yourself (DRY)

Avoid code repetition by introducing helper functions to reduce redundancy and improve maintainability.

The printUserInfo and printManagerInfo functions below repeat similar logic, violating the DRY principle:

func printUserInfo(user User) {
    fmt.Println("Name:", user.name)
    fmt.Println("Email:", user.email)
}

func printManagerInfo(manager Manager) {
    fmt.Println("Name:", manager.name)
    fmt.Println("Email:", manager.email)
}

To adhere to DRY principles, use a generalized printInfo function that operates on an InfoProvider interface:

type InfoProvider interface {
    GetName() string
    GetEmail() string
}

func printInfo(info InfoProvider) {
    fmt.Println("Name:", info.GetName())
    fmt.Println("Email:", info.GetEmail())
}
Summary

In this lesson, we learned that clean functions are key to maintaining readable and maintainable code. By keeping functions small, adhering to the Single Responsibility Principle, limiting arguments, avoiding side effects, and embracing the DRY principle, you set a strong foundation for clean coding. Next, we'll practice these principles to further sharpen your coding skills! 🎓

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