Validation belongs in the domain model, not the MVC framework

In the Java world validation almost always seems to happen in the MVC
framework. For example submitting a form causes some validation to
occur on the form and then if all checks out the domain objects are
populated and saved. I’ve never been crazy about this approach but
Hibernate doesn’t really address the validation issue and most of the
MVC frameworks do, so that’s often the easiest place to put it. The
problem is that most applications have numerous paths to load data
including web services, web pages, bulk data loading tools, etc… and
if your validation is all tied to your MVC framework you can’t easily
reuse it in the non-web paths.

Using Ruby on Rails has convinced me that putting your validation in
the domain model is generally the best approach. With Rails using
ActiveRecord that’s how it’s done and when the object fails to validate
those validation errors can be returned in a web form, data loading
tool, web service, etc… The validation is centralized and just
happens by default. As long as I get the validation right then I don’t
need to worry about another programmer writing a web service to
populate data and all of a sudden we have bad data in the database.

Here’s an example of one of my active record domain model classes with validation built in.

class Entry < ActiveRecord::Base

# Relationships
belongs_to :bliki

# Validation
validates_length_of :name, :within => 6..100
validates_uniqueness_of :name
validates_format_of :name, :with => /^\w+$/,
:message => “cannot contain whitespace”
validates_length_of :content, :minimum => 10
validates_associated :bliki

If you know of a good way to add validation to domain model objects in
Hibernate that gets called whenever a save or update is attempted
(perhaps via interceptor) I’d like to hear about it. I’d really like to
find an ActiveRecord style validation approach for Hibernate!

This entry was posted in Software Engineering. Bookmark the permalink.