I have a (common) situation where I am currently returning a result that is a mixed type, sometimes a boolean, sometimes an error message. For example:
function checked_thing_is_legal(){
// Do stuff and check for errors in here.
} // Returns true if there are no errors, otherwise returns an erro开发者_如何学Gor message string.
This feels dirty, and someone once said "it's good to distill code down to single, reliable return values", which I find to be good advice. So what is a better paradigm to check for errors?
i see two options here
use atomic (boolean) validators and decouple error messages from the validator itself
if(!is_valid_email(blah)) print "invalid email";
use validator objects with boolean test() and string error() functions:
$v = new SomeValidator;
if(!$v->test(blah))
echo $v->error();
in a quick and dirty application you can also consider returning an empty value if everything is ok
$err = validate_email(blah);
if(empty($err)) ok else print $err;
PHP Exceptions would be one classic way of doing it...
You have the following possibilites:
- Implement a switch checking for the type
- Create Exceptions/classes for each type (http://php.net/manual/en/language.exceptions.php)
- .
精彩评论