0

Imagine that I have a method like User::validate($data), and mostly the developer expects only that is returns a boolean (true mean "ok, validated with success"). But, in some specific cases, he need check why validation failed. What is the best way to check that?

I thought in following ways:

  1. Use an argument like User::validate($data, $throwsException = false) that when true, will throws an exception if it fail -- instead of returns false;
  2. Always throws an exception. So the developer need care about in catch exceptions of this method -- I personally don't like that;
  3. Instead of returns a boolean, returns a string or const (like FAIL_INVALID_NAME), but uses true as success -- or another const, like SUCCESS;
  4. Create an additional method like User::validateWithException($data) that, if it fails, throws an exception instead of return false;
  5. Create an additional method like User::validateReason($data) that will returns a string with the validation result -- like fail:invalid-name or success;
  6. Create an additional method like User::getLastError() that will returns a string or const with last error ocurred on class User, like after the validation method;

1 Answers1

1

A few of your cases above suggest throwing an exception when a validation fails. This is typically not recommended as exceptions should be reserved for exceptional cases (e.g., service not available, timeouts, etc) and not normal program flow. Also, exceptions are typically expensive operations.

Validations are expected to fail when the conditions are not met and should return values indicating this.

Per your question on what this should look like, one option would be to update your input and output to objects with a few properties. Perhaps something like:

ValidationRequest

  • $Data
  • $StopOnFirstFailure
  • Other validation behavior controlling properties

ValidationResponse

  • $Success
  • $FailureReasons

Take a look at one of the many validation frameworks out there and you'll see how these patterns are used.