There are a lot of opinions on how return
statements should work.
- Some say that there should be a single point of
return
in a function, - Some day we should
return
as early as possible, - Some day multiple
return
statements are fine, - And some say that, when applicable,
return
as early as possible.
I’m sure I’m missing some, but all of these are ones I’m sure the majority of you have seen. And though I don’t hold either of these to be law, I think there’s a time and a place for each.
I’m a fan of the early return
statement. In my mind, the sooner we can determine we don’t need to do the work of a function, the better we just leave.
For example, say we know if we’re not on a certain page, we can go ahead and leave the function:
In this case, it makes sense because:
- You only want to perform work on the
plugins.php
page, - The amount of work to be done in the function is larger than what should ever fit within a conditional.
But there’s an alternative when the amount of work is less than what’s above.
Don’t Perform an Early Return
Say for example you’re working with the activate_plugin
or deactivate_plugins hooks. Further, you have a class responsible for managing the cache.
When this is the case, the code may look something like this:
But it’s longer than it needs to be, returns
early when it doesn’t have to do, and can be consolidated into something that’s easier to read and makes for a smaller function.
For example:
The gist of it is this:
- The conditional can be negated,
- The work that was to be done after the early
return
can be moved into the conditional, - And we get smaller, clearer code.
This is but one example as to when/or this can be used; however, it’s worth considering if your could couldn’t be abstracted even further. That is, if you have code that could be wrapped in a function that creates a higher level of conhesion, maybe you should do that and then remove the early return
statement. Or maybe not.
I don’t know the use case for your specific code or what you’re trying to build. But the point is that I recommend don’t perform an early return unless it makes the code easier to follow.