Arun Pratap Singh
Arun Pratap Singh

Reputation: 395

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"

Upvotes: 4

Views: 105

Answers (3)

Fakhruddin Ujjainwala
Fakhruddin Ujjainwala

Reputation: 2553

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.

Upvotes: 0

Alexis Peters
Alexis Peters

Reputation: 1631

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

Upvotes: 3

Jerry Don
Jerry Don

Reputation: 11

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

Upvotes: 0

Related Questions