Code Refactoring: Avoid Nested If Statements with Early Returns

RMAG news

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’;
}
}

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’;
}

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.

Please follow and like us:
Pin Share