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.

Top comments (0)