Simple Object Validation in Java

Viewed 13196

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 }
}
5 Answers
Related