Which approach is better to return true or false?

Maybe my question is not important, but it appears in my head when I work on my project. So I want to know which one is better suited in terms of performance, and I also want to know if there are any other side effects.

Code 1:

if ($result === TRUE){
    // some statements 
    return TRUE;
}else{
    // some statements
    return FALSE;
}

Code 2:

if ($result === FALSE){
    // some statements
    return FALSE;
}

// some statements
return TRUE;

Note that I need to process some code when the condition is true or false, so I posted a comment stating that "// some statements

+4
source share
3 answers

The performance of both is the same. Choose the one that is better to read, the first one can make you get a V-shape, for example

if($result) {

} else {
  for() {
    if($result2) {
      //code
    }
  }
}

, ,

+3

return $result === TRUE? TRUE: FALSE;

0

I always follow this pattern:

// declare result as true by default
$result = true;

// some logic that will decide on the status of result

if (!$result) // this is same as $result === false
{
    return $result = false;
}

return $result;

Benefits:

The rest of the block is skipped. Therefore, less code, but this does not work if you need an else block.

0
source

Source: https://habr.com/ru/post/1626964/


All Articles