Reputation: 2500
Many domain objects in our home project need field validation and we use commons-lang for this purpose. For example:
public class Position {
private static final int LATITUDE_AMPLITUDE = 90;
private static final int LONGITUDE_AMPLITUDE = 180;
private Float latitude;
private Float longitude;
public Position(float latitude, float longitude) {
Validate.inclusiveBetween(-LATITUDE_AMPLITUDE, LATITUDE_AMPLITUDE, latitude,
"Latitude must be +- " + LATITUDE_AMPLITUDE);
Validate.inclusiveBetween(-LONGITUDE_AMPLITUDE, LONGITUDE_AMPLITUDE, longitude,
"Longtitude must be +- " + LATITUDE_AMPLITUDE);
this.latitude = latitude;
this.longitude = longitude;
}
}
We decided not to use JSR 303 because it couples domain objects with infrastructure and requires external intervention that will fire validating.
But when we started to implement REST endpoints, we faced the validating problem again, since json converters doesn't use class constructor, but inject values via Reflection.
It's very easy to validate objects via JSR303 and Jersey's @Valid
annotation, but it requires to annotate domain objects with JSR303. And we have here some options:
new
) JSR303 validation triggering.What is you opinion about this? Is it good way to mix both, JSR303 and manual validations?
Upvotes: 1
Views: 671
Reputation: 5443
Having worked extensively with both models, I personally find JSR 303 bean validation much more of a pleasure to work with. By this I mean purely using bean validation annotations, with no manual validation code.
Bean validation annotations decouple the validation logic from the domain entities themselves. I believe this is a good thing because it reduces boilerplate code in your domain entities, and makes them more readable and maintainable. As you mentioned, it does require that you annotate the fields in your entities in order to use it. Depending on the size of your existing codebase, this work could be non-trivial.
Most of my experience has been with Hibernate Validator, which I've found to be a good, fast JSR 303 implementation.
Upvotes: 2