12.10.06
Validation in a (Web) Application
Glen has a short tutorial on how to perform validation using Spring Valang (which is part of Spring Modules, which provide additional modules to integrate external projects with Spring, like OSCache, etc..) . While it is certainly better practice to choose XML validation instead of writing Validator classes manually, I personally prefer the @Annotations approach that is possible using Webwork / Struts 2.
Not only does it make people more productive by avoiding the need to edit 5 files at the same time (The Java class + the HTML/JSP/Freemarker template is all we should need to edit while creating a web application… Take a look at Tapestry 5 ), but it also shows the validation code at the same place at the code, and thus helps to maintain both.
However, I believe both approaches are not the way to go. We all use the validation features provided by our lovely MVC frameworks because it is handy, but when you think about it, validation should be part of the domain. The domain classes should be intelligent, they should have as much behavior as possible, and validation is one of the thing the domain should provide, in order to maintain integrity. For instance, if a domain layer has 2 User Interfaces (Web, and Swing, let’s say) interacting with it, the validation rules should only be implemented once, in the domain, not twice, because the integrity checks must be centralized.
But the frameworks are not quite there yet :
- Declarative (using annotations, for instance) is built into MVC frameworks and as such, are only tightly integrated to the view, not the domain. So, it requires more efforts to do validation on the domain. (Think of it as Spring MVC or Webwork validation, that automatically returns to the form and repopulates the data in case of an error VS throwing an exception that you have to handle manually)
- Validation defines constraints, and as such, is best expressed declaratively. However, if one wants to check constraints in the domain, it is necessary to either programmatically do it, or use AOP (maybe coupled with Annotations) to do so. However, it is still unclear whether AOP is a good thing to implement domain features. Lots of people tend to think of AOP as a way to implement cross-cutting TECHNICAL concerns, such as security, cache, or transaction demarcation.
Has anyone ever thought about that issue ? Have you implemented (programmatic) domain validation (maybe using Hibernate Validator, which is limited to persisted classes ?) on a real-life project ? What do you think about it ?