With respect to coding standards, speed, and efficiency, which of the following is a better programming practice for this situation?
function foo() {
if(bar) { return 0; }
if(baz) { return 0; }
if(qux) { return 0; }
}
or
function foo() {
if(bar || baz || qux) { return 0; }
}
I’d lean toward the first, since only one condition has to be evaluated and therefore would be faster, but having the multiple returns is not good…?
//EDIT
The languages I’d be applying this to are mainly PHP and Javascript, possibly C++ and Ruby.
Almost every single programming language today uses short-circuit evaluation for
||, which means the two examples will be equivalent in terms of control flow and thus performance.Having multiple returns should indeed be avoided if they are spread all over the function and they return different things, because this decreases readability. On the other hand, it’s fairly standard to have early-out conditions that detect inacceptable conditions and stop the execution flow: