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.
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.
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.
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.