Check class - should return a false or throw exception?

I am creating a class that checks strings. There are many reasons why a line may not go through.

Would it be more appropriate to throw an exception or return an error / error code? Pros / Cons?

+6
source share
3 answers

validators should not throw exceptions, as refusal of verification is not an "exceptional" event.

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

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

+8
source

Return false .
An exception is an EXCLUSION, and it should be thrown only in exceptional cases when the script cannot continue execution.

+3
source

Throwing an exception seems a bit extreme, since a line that does not check is not really an exception to the string check package.

As such, I would think that returning the false would be the most logical solution. In addition, you can also pass a significant textual error through a reference variable, if that makes sense with respect to your implementation.

For instance:

 // 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); 
0
source

Source: https://habr.com/ru/post/889039/


All Articles