Alternative to return mixed errors and booleans

I have a (general) situation where I am currently returning a mixed type result, sometimes logical, sometimes an error message. For instance:

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. 

It feels dirty, and someone once said, β€œIt's good to bring the code to a simple, reliable return value,” which I think is good advice. So what is the best paradigm for error checking?

+4
source share
3 answers

Here I see two options.

use atomic (logical) validators and separate 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; 
+5
source

Exceptions PHP will be one of the classic ways to do this ...

+1
source

You have the following options:

0
source

All Articles