Skip to content

Instantly share code, notes, and snippets.

@gavinblair
Created November 18, 2010 18:52
Show Gist options
  • Select an option

  • Save gavinblair/705417 to your computer and use it in GitHub Desktop.

Select an option

Save gavinblair/705417 to your computer and use it in GitHub Desktop.
Which method is better?
<?php
function myfunction(){
if($somecondition) {
...
... //many lines of code
...
} else {
return false;
}
}
/* OR */
function myfunction(){
if(!$somecondition) {
return false;
}
...
... //many lines of code
...
}
@zoster
Copy link

zoster commented Nov 18, 2010

I like the second one better, because it's harder to lose the if's closing bracket :)

@SeanJA
Copy link

SeanJA commented Nov 18, 2010

They aren't the same, one will return false, one will not

@gavinblair
Copy link
Author

@SeanJA how about now?

@SeanJA
Copy link

SeanJA commented Nov 18, 2010

Me thinks...

<?php
//multiple returns (possibility of deleting one by accident)
function myfunction(){
    if($somecondition) {
        ...
        ... //many lines of code
        ...
        return $return;
    }
    return false;
}

/* OR */
//multiple returns (possibility of deleting one by accident)
function myfunction(){
    if(!$somecondition) {
        return false;
    }
    ...
    ... //many lines of code
    ...
    return $return;
}

// or ---
//single return point
function test(){
    $return = false;
    if($condition){
         //many lines of code
        $return = $somethingElse;
    }
    return $return;
}

@gavinblair
Copy link
Author

The main issue was wrapping 99% of your function in an IF means there is the possibility of deleting one of the }'s by accident.

@SeanJA
Copy link

SeanJA commented Nov 18, 2010

replace //many lines of code with //function_call :P

@gavinblair
Copy link
Author

haha ya. really, if the entire function is an if statement, then the if could be put around the call.

@gavinblair
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment