Wednesday, November 2, 2011

Validation with pure Java - 3


For the sake of keeping the code compact, the ConstrainedObject provides a method that validates int properties only. You can easily overload this method for the other types as well. If you do so, just make sure to wrap all the primitive types in their respective wrappers since PropertyChangeEvent delivers old and new values as references types. Now you are ready to issue a second revision of the BusinessObject:
import java.beans.*;
/**
 * This example class actually uses data-validation services defined in this framework.
 */
public class BusinessObject extends ConstrainedObject {
  private int numericValue;
  public void setNumericValue(int newNumericValue) throws PropertyVetoException {
    // validate proposed value
    validate("numericValue", numericValue, newNumericValue);
    // the new value is approved, since no exceptions were thrown
    numericValue = newNumericValue;
  }
  public int getNumericValue() {
    return numericValue;
  }
}

As you see, the setter method now looks a bit more complicated than before. It is a small price to pay for having a constrained property. Now you must build a Validator, which is the most interesting part of this exercise. This is where you learn how to externalize data-validation rules using nothing but pure Java.
import java.beans.*;
public class Validator implements VetoableChangeListener {
  public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
    // do the validation here
  }
}

No comments: