I'd like to ask a question about Beans and Validation. Feel free to use it is a blog post.
So a lot of people have been telling me that Beans could/should have a validate() method to validate their own data.
My issue with this is, how can a bean validate it's own data if it is throwing errors in get() methods because you are trying to insert invalid data.
Since I cannot insert "Jason" into a date var or a numeric var, what good is my bean's validate() method gonna do me.
It seems to me that I have two choices.
1. I can do pre-validation validation. And validate the data before I insert it into the bean for validation
2. I can do all of my validation in the service layer or handler/listener(if no service layer) and THEN populate my bean with valid data.
I like option 2.
Am I making sense?
FYI, I am an OO n00b.
Hi Jason, don't worry, you're making sense. I actually don't do either of these. Before I do anything like a save() of an object, I create a Result object. My Result is a generic object with methods like isSuccess(), hasErrors(), getErrors(), etc. I use this to handle my validation.
Basically, I call user.populate(data, result). The populate function attempts to populate the object by calling setters that correspond to the data that was passed. (For customization, an object can override it's inherited populate() method if the generic behavior isn't sufficient.) If there are any failures, an error is caught and added to the Result object.
Once that is done, attempt to save the object even if there are errors, so that I can get additional validation error messages (i.e. end date must be after start date). Saving is done the same way: user.save(result). The save() call triggers a validation, and any validation errors not based on type are added to the Result as well. If the Result contains no errors after validation, I proceed with the save. If there are errors, the save does not continue.
Once that is done, I have a Result object that either has errors or it doesn't. These may be population errors cause by type mismatches, or they may be validation errors handled by my validation rules. Regardless, I now have a nicely packaged Result object that I can return to the calling code. This can be returned to something like Flex, or it can be returned to an HTML Controller such as Model-Glue, but either way, that code can now decide how to proceed.
This is just the way I do things but I've found it to be very flexible and useful. I hope that helps!