Welcome

Mojo
Posts about photography, contract bridge, astrophotography, astronomy, Java development, internet systems.

“Bean Validation” Emmanuel Bernard

Registration lobby at Caesar's Palace

Registration lobby at Caesar's Palace

Notes from TheServerSide Java Symposium March 2009

What’s the point of a bean validation framework? I’ve been wondering that for a while now. Emmanuel points out that it’s mostly to keep from repeating yourself in code.

Validation itself is obvious … keep crap out of the database, apply constraints to data fields, give feedback to users.

Where do we apply validation constraints? Take a typical application stack:

client -> presentation layer -> business layer -> data access layer -> database

He begins by giving several examples of how constraints are applied to day, down to the DDL in the database which might specify a column length and a “not null” constraint. These constraints are typically duplicated all the way up the application chain, and really bad when the constraints don’t agree!

He proposes a uniform way to express a constraint, a standard way to validate constraints, and a bridge for constraints out of Java land, exposing constraints to the outside world.

Annotations are the key, extending the type system, right next to the class definition. Hence JSR 303 for bean validation. Example field annotations for validation:

@NotNull
@Size(max=30, message="longer than {max} characters")

The spec also calls for validating subsets of data fields by specifying groups, or partial validation. The spec defines groups by using interfaces. Clumsy, but workable.

Custom constraints can be built out by creating a custom annotation with an expressive name, extending the @Constraint type. You can compose a group of existing validators from the library into a new annotation.

(So far I’ve only been a consumer of annotations. Maybe soon it will be time for me to start creating them as well. I usually try to avoid meta-programming, even though it can be fun.)

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>