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 and methods, 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 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 method, which is manageable but has the potential to become unwieldy over time:

public void 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 private method, as shown below:

public void ProcessOrder(Order order, Inventory inventory, Logger logger)
{
    if (!ValidateOrder(order, logger)) return;
    if (!ProcessPayment(order, logger)) return;
    UpdateInventory(order, inventory);
    NotifyCustomer(order);
    LogOrderProcessing(logger);
}

private bool ValidateOrder(Order order, Logger logger)
{
    if (!order.IsValid())
    {
        logger.Log("Invalid Order");
        return false;
    }
    return true;
}

private bool ProcessPayment(Order order, Logger logger)
{
    if (!order.ProcessPayment())
    {
        logger.Log("Payment failed");
        return false;
    }
    return true;
}

private void UpdateInventory(Order order, Inventory inventory)
{
    inventory.Update(order.Items);
}

private void NotifyCustomer(Order order)
{
    order.NotifyCustomer();
}

private void 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 method, which is both too lengthy and does multiple different things at once:

public void SaveAndNotifyUser(User user, DataSource dataSource, HttpClient httpClient)
{
    // Save user to the database
    string sql = "INSERT INTO users (name, email) VALUES (@name, @Email)";
    
    using (var connection = dataSource.GetConnection())
    using (var command = new SqlCommand(sql, connection))
    {
        command.Parameters.AddWithValue("@Name", user.Name);
        command.Parameters.AddWithValue("@Email", user.Email);
        connection.Open();
        command.ExecuteNonQuery();
    }

    // Send a welcome email to the user
    var content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
    var response = httpClient.PostAsync("/sendWelcomeEmail", content).Result;
    if (!response.IsSuccessStatusCode)
    {
        throw new Exception("Failed to send email");
    }
}

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

public void SaveAndNotifyUser(User user, DataSource dataSource, HttpClient httpClient)
{
    SaveUser(user, dataSource);
    NotifyUser(user, httpClient);
}

private void SaveUser(User user, DataSource dataSource)
{
    string sql = "INSERT INTO users (name, email) VALUES (@name, @Email)";
    
    using (var connection = dataSource.GetConnection())
    using (var command = new SqlCommand(sql, connection))
    {
        command.Parameters.AddWithValue("@Name", user.Name);
        command.Parameters.AddWithValue("@Email", user.Email);
        connection.Open();
        command.ExecuteNonQuery();
    }
}

private void NotifyUser(User user, HttpClient httpClient)
{
    var content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
    var response = httpClient.PostAsync("/sendWelcomeEmail", content).Result;
    if (!response.IsSuccessStatusCode)
    {
        throw new Exception("Failed to send email");
    }
}
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 method below with five arguments, which makes the function less clean:

public void SaveAddress(string street, string city, string state, string zipCode, string country)
{
    // Logic to save address
}

A cleaner version encapsulates the details into an Address object, reducing the number of arguments and making the method signature clearer:

public void SaveAddress(Address address)
{
    // Logic to save address
}
Avoid Boolean Flags

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

The SetFlag method below uses a boolean flag to indicate user status, leading to potential complexity:

public void SetFlag(User user, bool isAdmin)
{
    // Logic based on flag
}

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

public void GrantAdminPrivileges(User user)
{
    // Logic for admin rights
}

public void RevokeAdminPrivileges(User user)
{
    // Logic to remove admin rights
}
Avoid Side Effects

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

Below, the AddToTotal method demonstrates a side effect by modifying an external state:

// Not Clean - Side Effect
public int AddToTotal(ref int total, int value)
{
    total += value; // modifies external state
    return total;
}

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

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

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

The PrintUserInfo and PrintManagerInfo methods below repeat similar logic, violating the DRY principle:

public void PrintUserInfo(User user)
{
    Console.WriteLine("Name: " + user.Name);
    Console.WriteLine("Email: " + user.Email);
}

public void PrintManagerInfo(Manager manager)
{
    Console.WriteLine("Name: " + manager.Name);
    Console.WriteLine("Email: " + manager.Email);
}

To adhere to DRY principles, use a generalized PrintInfo method. Ensure that both User and Manager inherit from a common Person base class or interface that includes Name and Email properties:

public void PrintInfo(Person person)
{
    Console.WriteLine("Name: " + person.Name);
    Console.WriteLine("Email: " + person.Email);
}

This approach ensures that both User and Manager can be printed using the PrintInfo method without code duplication.

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