Home » Php » php – Validation Class – should return false or throw exception?

php – Validation Class – should return false or throw exception?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am creating a class that validates strings. There are many reasons why the string might not pass.

Would it make more sense to throw an exception, or return false/error code? Pros/cons?

How to&Answers:

validators should not throw exceptions, as failing a validator is not an “exceptional” event.

the rest of your code should throw exceptions if it gets bad data.

when you run a validator function you are clearly prepared to handle any problems detected with a simple test. wrapping everything in a try/catch block and stopping all execution only to try to recover is overkill. Just use and if statement, and be prepared to show the user some error messages.

Answer:

Return false.
Exception is EXCEPTION, and should be thrown in exceptional cases only, when script can’t continue execution.

Answer:

Throwing an exception seems a bit extreme, as a string not validating isn’t really an exceptional event as far as a string validation suite is concerned.

As such, I’d have thought that returning false would seem the most logical solution. Additionally, you could also pass back a meaningful textual error via a reference variable, if this makes sense as far as your implementation is concerned.

For example:

// In the class definition...
public function validateSTring($stringToValidate, &$errorString=null) {

    // If an error occurs...
    if($errorString) {
        $errorString = 'Something went wrong along the way.';
        return false;
    }     

}


// When calling...

$errorString = '';
$validationSuite->validateString($stringToValidate, $errorString);