php · level 3 · unit 4 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Check inputs at the door, and bad data never gets inside.
A sits at the very top of a function. If the input is wrong, it throws straight away and the rest of the function never runs. This is how you : one clear error now beats a mystery bug three files later.
Put guards in a constructor and you get a , a small immutable object that can only hold a valid value. Once an Email exists, it is valid, so every function that asks for an Email can skip checking it ever again.
<?php
class Email {
public readonly string $address;
public function __construct(string $address) {
$address = strtolower(trim($address));
if (filter_var($address, FILTER_VALIDATE_EMAIL) === false) {
throw new InvalidArgumentException("Not an email: $address");
}
$this->address = $address;
}
}
function welcome(Email $email): string {
return "Welcome email sent to $email->address";
}
echo welcome(new Email(" Sam@Example.COM ")) . "\n"; The value object tidies its input too, so every Email is lowercase with no stray spaces.
guess first
Three withdrawals, two guards. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
function withdraw(int $balance, int $amount): int {
if ($amount <= 0) { throw new InvalidArgumentException("Amount must be positive."); }
if ($amount > $balance) { throw new RuntimeException("Not enough money."); }
return $balance - $amount;
}
try {
echo withdraw(50, 20) . "\n";
echo withdraw(50, 80) . "\n";
echo withdraw(50, -5) . "\n";
} catch (Exception $e) {
echo $e->getMessage() . "\n";
}
your turn
Your turn. Only allow one to five stars.
Type the highest number of stars allowed in the first blank. In the second, pick a rating the guard should refuse.
fix it
The bill splitter checks too late. Fix it.
- The run dies with a
DivisionByZeroErroron line 3, before the guard on line 4 ever gets a look. - A guard clause only protects the code below it. This one is standing behind the very line it should protect.
- Move line 3 down so it comes after the guard's closing curly bracket, then run it.
nailed it
bad data stops at the door now. :D
- Guard clauses check inputs first and throw straight away.
- Fail fast: a clear error now beats a mystery later.
- A value object can only ever hold a valid value.
new words in your collection
- guard clause
- fail fast
- value object
This lesson isn’t saved. A free account remembers every lesson you finish.