Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to throw an exception on Validate() methods or better to return bool value?

Is it recommended or not to throw exceptions from Validation methods like:

ValidateDates(); ValidateCargoDetails(); 

Apart from this : Is there a robust validation design pattern often used?

like image 597
pencilCake Avatar asked Mar 08 '11 10:03

pencilCake


People also ask

Why is throwing an exception better than returning an error value?

Return codes are more brittle The error is ignored when "returned", and will possibly explode later (i.e. a NULL pointer). The same problem won't happen with exception. The error won't be ignored.

Is it a good approach to throw an exception?

The short answer is NO. You would throw an exception if the application can't continue executing with the bad data. In your example, the logic is to display an error message on the front end and Option 2 is the cleaner method for achieving this requirement.

When should a method throw an exception?

In short: You should throw an exception if a method is not able to do the task it is supposed to do.


2 Answers

I would suggest returning a ValidationResult object containing ValidationFailures. You should never use exceptions as part of your logical coding. Exceptions are for exceptions

like image 72
Andrew Avatar answered Oct 11 '22 12:10

Andrew


I would say it all depends on what/how you are doing the validation. But at the end of the day a developer can always choose to ignore a returned result (this is the problem with them), they can't ignore an exception without writing explicit code to do so.

like image 44
bytedev Avatar answered Oct 11 '22 12:10

bytedev