Programming can be considered as a form of art - like each artist does its own thing it is the same with coding style - each for their own. Sometimes you learn from others, and sometimes you discover it yourself or you combine different ways and see what works well and what does not.
I have an OCD when it comes to coding - everything needs to look tidy and this has pushed me to do things as best I can and even refactor old code so it looks nice and IDE doesn't complain about it anymore, I hate those highlights and underlines PhpStorm is throwing at me. So, over time I have developed my style which has been influenced by Drupal standards as I have worked on it most of the time, other developer code I find good looking and my personal experience.
The main topic of this article - guard clauses or early returns, is one style that I have used for a long time already and I did not have any idea that his way of doing things has an actual name.
The main idea is to reduce complexity - you will add one or more conditions and break the function execution flow by returning the function or breaking the loop. It is a step-by-step checking if everything is in place before continuing to the main logic. It will also improve readability by reducing indentation, so things are not nested anymore and it is more understandable what happens in the code.
Let's take an example - what you probably write normally (simplification):
function doSomething(array $param): int {
$return = 0;
if (!empty($param) {
foreach ($param as $item) {
if ($item['status'] === 0) {
$return = 1;
}
}
}
return $return;
}
For me, it looks a bit cramped, although readable and understandable, but I don't prefer that style. With guard clauses which I do prefer, the same thing looks something like this:
function doSomething(array $param): int {
$return = 0;
if (empty($param) {
return $return;
}
foreach ($param as $item) {
if ($item['status'] !== 0) {
continue;
}
$return = 1;
}
return $return;
}
The logic did not change, but the code structure changed. Things are now spaced out and look cleaner. The main goal of the guard clauses is to reduce clutter and complexity and the real benefit can be seen in larger functions where developers tend to write a lot of functionality inside one method/function. Because one downside of this is that the method/function can do one thing basically (you need to return or throw an exception if something is different from what you expect), it forces you to separate multiple functionalities
Overall, I'm satisfied with this structure and most of my code looks like this. The only problem I have seen is the hooks in Drupal, where half of the time you need to implement different types of logic and can't simply return the function (although you can write helpers to separate functionality).
More examples and information about it can be found here.