views:

37

answers:

3

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 error 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?

+1  A: 

PHP Exceptions would be one classic way of doing it...

Steven Schlansker
A: 

You have the following possibilites:

daemonfire300
+3  A: 

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;
stereofrog
+1 for not recommending exceptions
Galen
@Galen.... I also did not recommend exception as first choice...^^ and by the way, the example does not look like someone "new" to php could understand it.
daemonfire300