views:

58

answers:

2

I was just inquiring about standard practices of argument validation syntax. I'm working with PHP as of currently, but anything that's considered a platform/language agnostic solution would be great.

As of currently, I'm aware of two pretty common syntax. For example (my preference):

function foo($a, $b, $c){
    if(!$a){ throw new Exception(); }
    if($b < 0){ throw new Exception(); }
    if(!check($c)){ throw new Exception(); }

    //do stuff with $a, $b, and $c

}

And alternatively:

function foo($a, $b, $c){
    if($a){
        if($b >= 0){
            if(check($c)){

                //do stuff with $a, $b, and $c

            }else{ throw new Exception(); }
        }else{ throw new Exception(); }
    }else{ throw new Exception(); }
}

In any case, if anyone knows of documentation that illustrates any sort of standards, or common practices regarding this, I would greatly appreciate a reference.

Of course, personal preferences and opinions are more then welcome, but reasoning for your choices would be an asset.

+4  A: 

I prefer the former example you give for a number of reasons:

  • Code doesn't get unnecessarily indented as it does with nested if statements.
  • Nested if statements can add a heap of complicated branches to the logic flow which become hard to manage
  • Pre-conditions get moved down lower by nature of if statements. I prefer to have all pre-conditions immediately at the start of the method

Design by contract is the general approach to ensuring certain conditions are met (usually through assertions) such as:

Assert.IsNotNull($a, '$a must not be null');

If the assertion fails, an exception is thrown with the specified message.

Using the same approach you can make certain assertions at the end of the method (post-conditions) to ensure the method executed as expected.

Michael Shimmins
Thank you Michael - That is the same method I prefer. Any suggestions of existing Assertion classes for validating/throwing exceptions? I assume that an effective Assertion class design, would extend the existing Exception class, correct? Any suggestions on where to start writing my own?
TomcatExodus
A: 

Alternatively, group the set of if tests together in a single "if statement":

function foo($a, $b, $c) {
    if ((!$a) ||
        ($b < 0) ||
        (!check($c))) {
       throw new Exception();
    } 

    //do stuff with $a, $b, and $c
} 
Mark Baker