简体   繁体   中英

which approach is better to return true or false?

May be my question is not important but It pop up in my mind whenever I do work on my project,So I want to know that which one is better approach in terms of performance and I also want to know are there 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;

Please note that I have to process some code when condition is true or false that's why I putted comment stating that "// some statements"

The performance of both is the same. Pick the one that's better to read, the first one can lead you to get a V Form like

if($result) {

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

so i would prefer the second one, which is much easier to read for advanced programmers, but a little confusing to beginners

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

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;

Advantages:

Else block is skipped. Hence less code, but this does not work if you are in requirement of else block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM