bg_image
header

Early Exit

An Early Exit is a programming technique where a function or algorithm terminates early when a specific condition is met. The goal is usually to make the code more efficient and easier to read.

Example in a function:

function getDiscount($age) {
    if ($age < 18) {
        return 10; // 10% discount for minors
    }
    if ($age > 65) {
        return 15; // 15% discount for seniors
    }
    return 0; // No discount for other age groups
}

Here, the Early Exit ensures that the function immediately returns a value as soon as a condition is met. This avoids unnecessary else blocks and makes the code more readable.

Comparison with a nested version:

function getDiscount($age) {
    $discount = 0;
    if ($age < 18) {
        $discount = 10;
    } else {
        if ($age > 65) {
            $discount = 15;
        }
    }
    return $discount;
}

This version introduces unnecessary nesting, reducing readability.

Other Use Cases:

  • Input validation at the start of a function (return or throw for invalid input)

  • Breaking out of loops early when the desired result is found (break or return)

An Early Exit improves readability, maintainability, and performance in code.


Created 18 Hours 17 Minutes ago
Algorithmus Early Exit Programming Source Code Software

Leave a Comment Cancel Reply
* Required Field
Random Tech

Subversion - SVN


Apache_Subversion_logo.svg.png