Java: Validate In Your Constructor

Andy Lulciuc
2 min readJul 23, 2019

--

Hypothetically, let’s say you need to make a CRUD service for Books. A Book has to have a genre, title, author and page count in order for your feature to run smoothly. The classic way to implement this class is to create an anemic POJO with a field for each attribute.

This will work, but let’s say you have a coworker that now needs to use your CRUD service to implement their own feature. Since the Book class is an anemic POJO, they don’t know what’s required of a Book. In order to understand what is required, they might need to look at your database table, dive into your CRUD service implementation or stop by your desk for a chat. See the problem? Time is needlessly wasted.

An effective way to remedy this is to add validation and documentation to your constructor. That way, your coworkers only have to look at your Book constructor’s comments to understand the constraints of the class. What this effectively does is define a single source of truth (DRY) for your class that will help with the maintenance and clarity of your contract. Moreover, if an implementer makes a mistake working with your class, they will get a clear and meaningful runtime exception to alert them. I.e. the resulting stack trace will lead you to an error in the object’s initialization, so it will be clear what the fix is rather than a potentially unclear exception due to a SQL constraint violation bubbling up.

A common alternative that I’ve seen for performing validation is to use something like Bean Validation. The issue I have with validation like this is that it clutters up your classes and it’s brittle. I.e. you need to add annotations to your class and also use a separate validator object to perform the validation defined by those annotations. It’s brittle because unlike constructor validation which is guaranteed to occur, validation through Bean Validation is not guaranteed because it needs to be explicitly invoked on the target object. Granted, some REST API frameworks like DropWizard make using this kind of validation appealing because of the HTTP error messaging cleanliness and ease of use, but for other things I think it should be avoided.

One important thing that you need to consider if you chose to do constructor validation, is that the class must be immutable. Since validation is done on object initialization, you can’t have the object’s state mutate because each mutation will require validation as well. This would get ugly and I recommend avoiding it. On the other hand, if you choose to do validation in mutator (setter) methods only, then this opens up the possibility for an object to be created in a partially complete state, which defeats the purpose.

--

--