Guard Clauses: Flatten Your Code
PHP

Guard Clauses: Flatten Your Code

Nested conditions turn code into a "staircase" that's hard to read and maintain. Guard clauses solve this elegantly.

The Problem

 
function processOrder($order, $user) {
    if ($order !== null) {
        if ($order->isPaid()) {
            if ($user->hasPermission('process_orders')) {
                // finally, the actual logic
                $order->ship();
                return true;
            }
        }
    }
    return false;
}

The Solution

 
function processOrder($order, $user) {
    if ($order === null) return false;
    if (!$order->isPaid()) return false;
    if (!$user->hasPermission('process_orders')) return false;
    
    $order->ship();
    return true;
}

The Principle

Fail fast — check negative scenarios first and exit early. Leave the main logic without nesting.

Where to Apply

  • return — exit function
  • continue — skip loop iteration
  • break — exit loop

Code becomes linear, like a book — you read top to bottom without jumping between nesting levels.

Афоризм дня:

Народ должен защищать закон как свой оплот, как охранительную свою стену. (501)
PHP
By den On June 10, 2025
13

Leave a reply

Realtime chat

New window

Get Newsletter

Featured Posts