I’m writing a function and wondered if it’s best (in regards to performance and coding practices) to handle returning conditions like this:
public function func_1() {
if ( true == $condition) {
// Do something
return true;
} else {
return false;
}
}
or this:
public function func_2() {
if ( false == $condition ) return false;
// Do something
return true;
}
Is there a benefit to encapsulating a bunch of code within an if/else (func_1) or is it best to get the quickest returns out of the way first (func_2)?
Any performance different will be so tiny that it will be very difficult to measure.
I would generally use the second version, simply because it avoids further nesting if you have additional conditions, but for a simple if/else it might be better to keep the else for clarity.
In other words: use what works for you!