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.
nargin in Argument ValidationThe nargin function returns the number of function input arguments given in the call to the currently executing function. When using function argument validation, the value returned by nargin within a function is the number of positional arguments provided when the function is called.
Specify varargin by using lowercase characters. After any explicitly declared inputs, include varargin as the last input argument . When the function executes, varargin is a 1-by-N cell array, where N is the number of inputs that the function receives after the explicitly declared inputs.
Use function argument validation in MATLAB® to declare specific restrictions on function input arguments. You can constrain the class, size, and other aspects of function input values without writing code in the body of the function to perform these tests.
MATLAB creates a cell array that contains all the values passed in for that argument. Functions can include only one repeating input arguments block.
I prefer the former example you give for a number of reasons:
if
statements. I prefer to have all pre-conditions immediately at the start of the methodDesign 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With