Writing readable PHP: decrease indentation by returning early
In this short post, I'd like to give you a tip on writing readable PHP.
When working older code, or code submitted through PRs, I sometimes see this pattern:
public function doSomething($someParameter)
{
/** can be any kind of test */
if ($someParameter === 0) {
// do the actual work
}
}
At the beginning of the function, there's a test being performed. The actual work is in the if
block.
This can be refactored by reversing the condition and using an early return.
public function doSomething($someParameter)
{
if ($someParameter !== 0) {
return;
}
// do the actual work
}
Doing this has a couple of benefits:
- A level of indention is lost. This alone makes it more pleasant to read. You don't need to keep in your head that the code is wrapped in something.
- Using an early return is great for humans too. When somebody reading your code is interested in the case concerning the early return, he or she doesn't need further that that early return. In the first example, there could still be some code to be executed after the if block.
- When you're respecting a line length limit (you should), you now have more characters available when performing the actual work.
This technique also works when there are multiple conditions. Consider this function:
public function doSomething($someParameter, $someOtherParameter)
{
/** can be any kind of test */
if ($someParameter === 0) {
if ($someOtherParameter === 0) {
// do the actual work
}
}
}
By using early returns, you can rewrite it to something more readable.
public function doSomething($someParameter, $someOtherParameter)
{
if ($someParameter !== 0) {
return;
}
if ($someOtherParameter !== 0) {
return;
}
// do the actual work
}
You may be tempted to rewrite combine that if statement.
if ($someParameter !== 0 || $someOtherParameter !== 0) {
In most cases, I don't do this for three reasons:
- Personally, I need more brainpower to parse this.
- It's easy to make mistakes (should I use
||
or&&
) when there are more conditions - Using early returns is easier to debug. You could put a breakpoint or dump statement inside those if blocks. That way, you know which condition causes an early return.
This post summarised: whenever you see some code executed within an if block, check if you can reverse the condition to lose a level of indentation.
What are your thoughts on "Writing readable PHP: decrease indentation by returning early"?