How to simply avoid “else” in PHP and other programming languages

3 years ago, I was installing PHP Mess Detector for the first time on my Laravel application and after testing somes rules I fall on one rule that changed my programing vision since :

“Else is never necessary and you can simplify the code to work without else.”

https://phpmd.org/rules/cleancode.html#elseexpression

The documentation has no hint on how to process to deal with it, normal, it’s not his purpose. However, by forcing myself not to use the “else”, and after reviewing code of my team (about ten people with different level programming and different framework) I noticed that it was the same cases that kept coming back where we let ourselves be tempted to use it. Let see when and how to bypass them !


First, the very worst use case that I could see:

if ($myCondition) {
  // do NOTHING !
} else { 
  // do something
}

So, we are already told that the “else” is never necessary and in addition we find portions of code where it is the “if” that becomes completely unused instead … That’s ironic ! Somes dudes losed her head here .

It’s the worst and the easiest to deal with at the same time, just reverse the condition:

if (! $myCondition) {
  // do something
}

The other frustrating use case is when we use the “return” statement:

function myMethod()
{
  if ($condition) {
    // do something
    return true;
  } else {
    // do something else
    return false;
  }
}

I think that we tend to forget that a “return” abort the method and that if we has a “return” inside an “if” we will never go into the rest of the code, we can therefore simplify by removing the “else” and reindent (Which is also something important !):

function myMethod()
{
  if ($condition) {
    // do something
    return true;
  }
  // do something else
  return false;
}

We can apply this logic with other “breaking” statement, like “continue” in “foreach”

foreach ($array as $value) {
  if ($condition) {
    // do something
    continue;
  } else {
    // do something else
  }
}

foreach ($array as $value) {
  if ($condition) {
    // do something
    continue;
  }
  // do something else
}

The ternary and null coalescing operators

often we use the if / else to assign variables like this:

if ($condition) {
  $var = 'Hello';
} else {
  $var = 'World';
}

Here, it’s not complicate to deal with it but the approach can change according to the context, we can do:

$var = 'World';
if ($condition) {
  $var = 'Hello';
}

or, I think it’s better, use a ternary operator :

$var = $condition ? 'Hello' : 'World';

In PHP, if our condition is to verify if some variable exist and is not null, for assign it, we can use the null coalescing operators since php 7.x :

$var = $canNotExist ?? ‘hello world’;

so if $canNotExist is null or undefined, $var would be ‘Hello World’, if he is ‘false’ or empty ($canNotExist = ‘’), it will be returned anyway.

We can also use method inside our operators:

return CONDITION ? $users->getAll() : $users->getSomes();

And also indent like this when the lines becomes to long:

return (CONDITION && CONDITION2)
  ? $users->myMethodNameABitTooMuchLong()
  : $users->myOtherMethodNameTooLong();

Note that we can definitely use the ternary for returning boolean inside a fonction but there is still a small tips sometimes forgotten …

function myMethod()
{
  return $shouldReturnTrue ? true : false;
}

We can simply return the condition directly like that!

function myMethod()
{
  return $shouldReturnTrue;
}

This behaviour can depend on the contexte or the langage, see this example with the ‘or’ operator

function myMethod()
{
  $a = null;
  $b = "something";
  return $a || $b; 
}

in PHP, myMethod will return true because $b worth “something” but in other langage like JavaScript, myMethod will return the string “something”, the variable which is true for him … subtle, isn’t it?

Laravel Eloquent and the “if” statement

It’s a small bonus content for this articles, since we saw we don’t have really need of the “else” I think funny to know that Eloquent help us to also avoid the “if” in your code with the method when() that seem really pretty since PHP 7.4 and the coming of arrow function, example:

function getUsers(Request $r)
{
  $users = app(User::class);
  if ($r->created_at) {
    $users->where('created_at', $r->created_at);
  }
  if ($r->username) {
    $users->where('username', $r->username);
  }
  return $users->get();
}

That a common use case of Eloquent and filter Request, since we have the arrow function we can simplify like this (We can use the when() before, but I consider him really nice since):

function getUsers(Request $r)
{
    return User::when(CONDITION, CLOSURE)
        ->when($r->username, fn($q)=>$q->where('username', $r->username))
        ->get();
}

Conclusion

Why avoid “else” in your code ? It work, it was made to be used, it intuitive … Personnaly, i was first interested by this concept like “It’s true ? we really don’t need this ?” and after practice (it’s a challenge in the beginning) I realized that 99% of the times when I deemed it necessary, I don’t use it anymore … Yes there is still some time when I cannot allow to fully refactor legacy code due to lack of time (or rather budget). But now I find better clarity in my code, more refined and with above all: only useful code, because the “else” sometimes encourages redundant instructions, however small it may be. And it may seem trivial, but I read the “else”, unconsciously or not. It is a visual load that can be prevented as for the “parasitic characters” in the writing of Curriculum Vitae, where we are told that the recruiter takes less than 1 minute to read and that it is then necessary to eliminate everything which is not useful and play with formatting to guide the reader. In short, without it, my code works just as well, it’s shorter and is a little more maintainable, so I do without it. There are plenty of other ways to refactoring your code, you just have to take a look at https://refactoring.com/catalog/ to see some, but this one, I found it particularly not intuitive, “don’t use basic programming functionality?” and yet it’s really easy points to earn.

Sumber: https://thomas-sanctorum.medium.com/how-to-simply-avoid-else-in-php-and-others-programming-language-ccd6a07c4e1

Tags: No tags

Comments are closed.