Member-only story
Writing PHP code that easier to read and extend…
3 min readFeb 21, 2024
Conditionals
Bad ❌
function doSomething($var1, $var2, $var3)
{
if(($var1 == false || $var1 == null) && ($var2 == false || $var2 == null)) {
if(($var3 == false || $var3 == null)) {
return false;
}
} else {
if(is_int($var1) && is_int($var2) && is_int($var3)) {
$result = $var1 + $var2 + $var3;
return $result;
}
}
}
The above example demonstrates a function with deeply nested conditionals, making it hard to read and understand. It checks for false or null values in a non-strict manner, which can lead to unintended behaviours due to PHP’s type juggling.
Good ✅
function doSomething(int $var1, int $var2, SomeClass $var3): int
{
if(!$var1) {
throw new BadVariableException();
}
if(!$var2) {
throw new BadVariableException();
}
if(!$var->someMethod()) {
throw new MethodException();
}
return $var1 + $var2 + $var3;
}
- Type hint your variables
- Return early
- Separate conditionals
- Remove unnecessary variable assignments
The above example simplifies the conditionals by using type hinting for function parameters and throwing exceptions for invalid inputs. This approach makes the function’s requirements clear and enforces input validation upfront, leading to cleaner and more reliable code.