Simple object validation in Java

I wonder what is the best practice for checking an object. Is there an additional argument against the case of one or two cases? Is there another way?

I'm not looking for any validation library, I just want to do a simple validation.

Case 1

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 2

 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 } } 
+7
source share
5 answers

If you just swallow an exception, and if the verification method is only private, then prefer case two , since you should not use exceptions for normal logic.

If you want the client to handle the exception you need, then use case one , but let it throw instead of swallowing.

+7
source

Here's an excellent article by Joel Spolsky to consider reading. Personally, I prefer the second case. Exception handling can become dirty IMO.

+2
source

Well in the second case, the validate method will never throw a ValidationException , so if you want to handle more than one exception (null, wrong format, ...), I would suggest you use the first one so that you can return a clear and useful message about an error.

+1
source

If you really perform only 1 field check, then Example 2 is better because it clears what is wrong with the object.

If you need more information about a validation error, or you need to go through a few validation errors, you can use the exception object as a container to pass this additional information.

+1
source

In another way, I think you can create this code using Aspect-oriented programming. The verification code you added is some issue that will ruin your business code. If you use the aspect, you can avoid code pollution with a verification code. You can link to this article http://www.developer.com/java/5-reasons-java-developers-should-learn-and-use-aspectj.html , which shows an example of using validation using aspects.

0
source

All Articles