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 }
}
If you are just swallowing the exception and if the validation method is only private, then prefer
case twosince you should not use exceptions for normal logic.If you want to let the client handle the exception, which you should, then use
case onebut let it throw instead of swallowing.