开发者

Alternative to returning mixed errors and booleans

开发者 https://www.devze.com 2022-12-13 21:56 出处:网络
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:

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)
  • .
0

精彩评论

暂无评论...
验证码 换一张
取 消