Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Object Validation in Java

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 }
}
like image 545
jk_ Avatar asked Jul 14 '11 14:07

jk_


People also ask

How do you validate a class object in Java?

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.. }

What is validation in Java with example?

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.

What is object validation?

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.

How do you validate data in Java?

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.


1 Answers

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.

like image 163
Leonard Brünings Avatar answered Sep 28 '22 06:09

Leonard Brünings