In this video, which is a part of the Mailcoach video course, Freek shows us how he refactors a complex if
-statement.
A technique which I nowadays also like using myself – especially in a React Component’s render
method – is to use early returns: instead of nesting if
-statements and using else
-statements, the function body uses singular if
-statements which abort the function’s execution early on in case some condition is/isn’t met. Like so:
public function doSomething($someParameter, $someOtherParameter)
{
if ($someParameter !== 0) {
return;
}
if ($someOtherParameter !== 0) {
return;
}
// do the actual work
}
💡 If you’re a PHP developer I’d recommend the video course to you as it contains some pretty good stuff, such as this video on Pending Objects for example.