Monday, October 31, 2011

Validation with pure Java - 1

Build a solid foundation for the data-validation framework with the core Java API

The idea of constrained properties in Java is not new. Since JDK 1.1, a legion of JavaBeans developers has used a powerful framework found in the java.beans package to enforce data-validation rules. Unfortunately, the rest of us -- who are not in the business of crafting "reusable software components that can be manipulated visually in a builder tool" -- quite often attempt to reinvent the wheel by abandoning the core Java approach in favor of various proprietary solutions. The externalization of data-validation rules is the area where you can see the most creativity. An interesting XML-based approach was recently proposed in the "Validation with Java and XML Schema" series of JavaWorld. While admiring XML technology, I believe that Java has everything needed to solve the issue in the most elegant way. To show you, I invite you to rediscover some of the real gems found in the java.beans package. They will help you build a few useful classes and learn a couple of interesting tricks.
The logic behind constrained properties in Java is quite simple. Before accepting a new data value, the object (owner of the constrained property) makes sure it is accepted by all interested parties that may veto it. Such a "request for approval" is delivered to every registered java.beans.VetoableChangeListener in the form of a java.beans.PropertyChangeEvent object. If one or more vetoes have been issued, the proposed data value is rejected. A veto is presented by a java.beans.PropertyVetoException. Generally speaking, the complexity of the rules enforced by those listeners has no limit and depends only on the project's requirements and the developer's creativity. The objective of this exercise is to learn how to deal with the most generic data-validation criteria that you can apply to most objects.

No comments: