I wonder, what is the best practice for object validation. Is there any extra argument against case one or case two? Is there another way?
I don't search for any validation library, I just want to do simple validation.
Case One
class A {
public void doSomething(MyObject o) {
try {
validate(o);
doSomethingUseful(o);
} catch (ValidationException e) {
Logger.getLogger().warn(e);
}
}
private void validate(MyObject o) throws ValidationException
{
if (o.getXYZ() == null)
throw new ValidationException("Field XYZ cannot be null");
}
private void doSomethingUseful(MyObject o) { //some funny stuff }
}
Case Two
class A {
public void doSomething(MyObject o) {
if (validate(o)) {
doSomethingUseful(o);
} else
Logger.getLogger().warn("Object is invalid");
}
}
private boolean validate(MyObject o)
{
if (o.getXYZ() == null) return false;
return true;
}
private void doSomethingUseful(MyObject o) { //some funny stuff }
}
Suppose we have a Person class, and for all the instances, we want that the first name and the last name be assigned and not left null : class Person { @Validation private String name; @Validation private String lastName; // .... other fields... // .... getters and setters.. }
JavaBeans Validation (Bean Validation) is a new validation model available as part of Java EE 6 platform. The Bean Validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component, such as a managed bean. Constraints can be built in or user defined.
Validation verifies the definitions of both data objects and ETL objects and identifies any problems or possible errors that could occur during deployment. If objects are invalid, generation and deployment is not possible.
In the Java programming language, the most natural way of doing data validation seems to be the following: try to build an object. if no problem is found, then just use the object. if one or more problems are found, then ensure the caller has enough information to tell the user about the issues.
If you are just swallowing the exception and if the validation method is only private, then prefer case two
since you should not use exceptions for normal logic.
If you want to let the client handle the exception, which you should, then use case one
but let it throw instead of swallowing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With