DEV Community

Cover image for Code Refactoring: Avoid Nested If Statements with Early Returns

Code Refactoring: Avoid Nested If Statements with Early Returns

The Problem with Nested If Statements

Nested if statements occur when multiple conditional checks are placed within each other. While nested if statements are sometimes necessary, excessive nesting can lead to "arrow code," which is difficult to read and understand. Here's an example of nested if statements:

function processOrder($order)
{
    if ($order->isValid()) {
        if ($order->isPaid()) {
            if ($order->isShipped()) {
                // Process the order
                return 'Order processed';
            } else {
                return 'Order not shipped';
            }
        } else {
            return 'Order not paid';
        }
    } else {
        return 'Invalid order';
    }
}

Enter fullscreen mode Exit fullscreen mode

The Concept of Early Returns

The early return technique involves checking for conditions that should cause the function to exit early. By handling these conditions first, you can reduce the nesting level of your code and make the main logic more visible. Here's how the previous example looks with early returns:

function processOrder($order)
{
    if (!$order->isValid()) {
        return 'Invalid order';
    }

    if (!$order->isPaid()) {
        return 'Order not paid';
    }

    if (!$order->isShipped()) {
        return 'Order not shipped';
    }

    // Process the order
    return 'Order processed';
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Using early returns simplifies how code is structured and avoid complex arrow code. This approach makes code easier to read, maintain, and in overall better in quality. By refactoring nested if statements with early returns, we will create cleaner and easier to understand code, which boosts productivity and reduces errors.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more