I
I
Ilya2021-08-05 21:23:32
PHP
Ilya, 2021-08-05 21:23:32

The if or switch construct?

The question is simple and stupid. Two versions of the same code. How would you write and why? The names of methods and variables do not matter.

if (
  $this->inComplete($oldStatus, $newStatus) ||
  $this->outComplete($oldStatus, $newStatus)
) {
  $this->action();
  $this->save();
}


switch (true) {
  case ($this->inComplete($oldStatus, $newStatus)):
  case ($this->outComplete($oldStatus, $newStatus)):
    $this->action();
    $this->save();
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Saboteur, 2021-08-05
@saboteur_kiev

in this particular case, switch is clearly not needed.
switch is needed when you have a variable that you want to compare with different values ​​and do different actions depending on this. And you generally write true as a switch condition, and case without completion is, from the point of view of readability, a very implicit OR.

F
FanatPHP, 2021-08-06
@FanatPHP

The second option is a good attempt, but not fully implemented. You have to write like this

(function() { 
    foreach([true] as $condition) {
        $condition = ($condition) ? true : false; 
        while ($condition) {
            switch (true) {
                case ($this->inComplete(($oldStatus), ($newStatus))):
                case ($this->outComplete(($oldStatus), ($newStatus))):
                    ($this->action());
                    ($this->save());
            }
            break;
        }
    }
})();

In general, before asking a question on the toaster, you need to sit down and first think carefully about what meaningless statements you can add to the code, except for switch.

P
Pavel Omelchenko, 2021-08-12
@pOmelchenko

If in which would call one wrapper method returning a bool value.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question