0

I've come across this problem a few times:

Is there any "programming rule" for checking for an condition (error checking for example) before you want to do execute code, or only execute the code when that condition is true.

Checking before running the code:

$condition = false;

function someFunction() {
    if(!$condition) {
      throw new Exception("Cant execute code because the condition is false"); 
    }
    //Execute code 
}

Only run the code when the condition is true:

$condition = false;

function someFunction() {
    if($condition) {
      //Execute code 
    } else {
      throw new Exception("Cant execute code because the condition is false"); 
    }
}

Question

Which one of the code examples is the most efficient however they're doing the same thing?

1 Answer 1

4

Check before, please. Which would you rather read and debug, after the code has been modified a few times.

This?

function someFunction() {
    if($condition1) {
       if($condition2) {
           if($condition3) {
              //Execute code 
            } else {
                throw new Exception("Cant execute code because the third condition is false");
            }
        } else {
            throw new Exception("Cant execute code because the second condition is false"); 
        }
    } else {
        throw new Exception("Cant execute code because the first condition is false"); 
    }
}

Or this?

function someFunction() {
    if(!$condition1) {
        throw new Exception("Cant execute code because the first condition is false"); 
    }
    if(!$condition2) {
        throw new Exception("Cant execute code because the second condition is false"); 
    }
    if(!$condition3) {
        throw new Exception("Cant execute code because the third condition is false");
    }
    //Execute code 
}
1
  • Thank you, does this occur in every case? Even if it's only 1 condition to check?
    – Bas
    Commented Jan 26, 2015 at 10:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.