This is more of a "discussion"/"asking for opinions" post, but since /r/java is so strict on what they allow, I'd thought I'd better ask here.
In a typical Java web application, we treat validation of incoming objects (for example, deserialized JSON) as an external step. By "external" I mean that the validation logic is a separate step to creating the object. For example, using the Jakarta validation API:
class User {
private firstName;
@NotNull @NotBlank
private lastName;
// getters/setters omitted
}
We could also make the class immutable and place the validation annotations in the constructor, but the point is that I can create an object while bypassing these validations.
Not a problem in a REST controller (unless you forgot the @Valid annotation and have no tests), but for example in test code you can freely create objects that violate these requirements. This has some problems:
the tests are less documenting. A new ISBN("I don't care") doesn't show me what a real-world ISBN number would look like.
Adding perfectly valid application code relying on validated properties can make tests fail that use arbitrary data. Let's say I expect an ISBN to have exactly 10 or 13 digits, and add code that does a substring() on that without a range check. If I create an object that violates this property in my test, the new code may fail.
And if you were as paranoid as the Secure Coding Guidelines for Java, each public method in each layer in your application would have to perform the validation again.
With Java putting more and more emphasis on integrity and strong encapsulation, and examples about adding validation logic to constructors like in the record JEP, I was wondering whether our approach to validation is flawed. Not having a blank "lastName" is an invariant of User, something that we should be able to rely on in every place where an instance of User is used.
So why not put validation into the constructor? For example, using a validation API like in this made-up example by ChatGPT:
public record Person(String name, int age) {
public static final Validation<String> NAME_VALIDATION = Validation.of(new NotEmpty("Name cannot be empty."));
public static final Validation<Integer> AGE_VALIDATION = Validation.of(new Min(0, "Age cannot be negative."));
public Person {
NAME_VALIDATION.validate(name).throwIfInvalid(IllegalArgumentException::new);
AGE_VALIDATION.validate(age).throwIfInvalid(IllegalArgumentException::new);
}
}
This prevents me from ever creating a new Person("John", -42). (The example API ignores concerns like localizing error messages, capturing the name of the field, etc. – it's just an example.)
So, what do you think?
Drawbacks I can see with this approach:
when adding a new constraint, old, unmigrated data in the database would not be mappable to the object. This can be solved by having different classes at API, core, and persistence layer, but you'd have to duplicate validations (or don't do them in all places).
you can only use self-contained validations in the constructor. If I want to check for example if a country code is in a list of codes I retrieved from a code dictionary service, I would either have to do this externally, or pass the list of valid codes to the object on construction, for example via a static factory method, which doesn't sound like clean code.
Theoretical performance impact by repeating validation when creating a copy, but I trust the JIT compiler in the JVM to inline as much as possible and optimize using predictive branching.