Where do you do validation in a webapp (backend)?
Option #1: Service layer?
UserService.validate(FORM); // verify and returns struct of errors
Option #2: Object layer, on setter? e.g.
user.setEmail(email); // throws invalid/used e-mail
Option #3: Object layer, validate()? e.g.
user.init(FORM); // accept any values, no type checking
user.validate(); // returns struct of errors
What’s your take? Thanks!
I typically keep my form validation in the service layer, rather than with the objects themselves. I do this not because I don’t agree with keeping the objects being wholly encapsulated, I do it because it fits the methodology/design pattern that I choose use in my sites for handling form submissions.
I think frameworks like Transfer encourage you to keep object validation within the objects where as engines/frameworks like Alegad’s Validat are designed to keep validation outside of it. I don’t think either approach is wrong, its really just a matter of what you prefer (and what fits the application).
Out of the 3 options though, option #2 is miss-use of exception handling for situations in which you have expected outcomes. By having a validate method (whether it be on the object or in a service) you can control the erroneous validation situations more gracefully than catching exceptions and bubbling them up passively (capture and return a struct with info on the failure) or explicitly (rethrow, ect..).