We are having a heated discussion about this at work:
For sake of simplicity, I will use examples in the question.
Assume there is an application with an account request form, for which we have these requirements:
- Dates and Email must match a regex
- If the user already has an account request, he should not request for another
The problem is: where to verify the second requirement?
-
If we check on the controller, we would have to access the database from there and it is a business logic, so it doesn’t seem right.
-
If we validate on the business layer, we would have to somehow return the validation information in case of a failed validation. Doing this would require either:
- Each business method to have an “out” parameter;
- We to encapsulate our return object into a “response” object with the validation information
- The use of exceptions in case of failed validations (which, to me, falls in the anti-pattern of using exceptions for programm flow).
How should we design this?
6
Go for the second solution. Your AccountRequestValidator
uses the db information and some rules to determine of the request is valid or not. Then use a “response” object, but don’t create one yourself if you use a language that has already implemented that for you like Scala or Haskell. This type is usually called Either
. It should throw an Exception if it is not able to check if the validation is valid, for whatever reasons there might be.
Your code would therefore look similar to:
AccountRequestValidator validator = new AccountRequestValidator(db)
AccountRequest request = //...
try {
Either<RequestAllowed, RequestForbidden> validationResult = validator.validate(request )
//Do sth. with validationResult
}
catch (Exception e) {
//Was unable to check if the request is valid...
}
If you use Java, consider using Googles Functional Java. It has its own Either
type defined.
3
Validating for format validity on single fields, should happen as close to the point of entry into your code as possible. In this case it should be as close to the UI as possible. One reason for this is that this allows you to assume proper values from that point on. Another is that this allows you to check before actually processing anything which brings functional benefits as well.
Validating stuff like, is this account already created is a whole different thing altogether and should reside in the business logic. To elaborate on your concerns here. Never ever use exceptions for logic! Exceptions are for exactly that, exceptions. Something unexpected went wrong so an exception occurs.
I personally am no fan of out parameters as well and would go for the response object. Also I would encourage you not to extrapolate functionality like this in a separate set of objects, where you can tailor your classes to closely mimic your functional needs instead of your data model.
HTH.
4