Primitive, self-validating immutable object types.
As proposed by Stefan Ludwig in his strongly-typed-vs-javax-validation prototype.
- 🚀 Features
- 📚 Releases
- 👩💻/👨💻 Contributing
- 📨 Contact
The ValueObject<T>
could be used to create a self-validating immutable object:
class Name extends ValueObject<String> {
public Name(String value) {
super(value, isNotNull().andThen(hasMinLength(3).andThen(hasMaxLength(20))));
}
}
It's only possible to create a valid object if it matches the pattern. The ValueObject
does only provide a getter resulting in an immutable object.
Creating a name object with an invalid value will throw an InvariantException:
class NameTest {
@Test
void should_create_valid_object() {
String nameValue = "Peter";
Name name = new Name(nameValue);
assertNotNull(name);
assertEquals(nameValue, name.getValue());
}
@Nested
class InvariantTest {
@Test
void should_throw_invariant_exception_if_value_is_null() {
InvariantException exception = assertThrows(
InvariantException.class,
() -> new Name(null));
assertEquals(
"Value(s) of Name is not valid: Name (null) should not be null. Name (null) should be longer than 3. Name (null) should not be longer than 20.",
exception.getMessage());
}
@Test
void should_throw_invariant_exception_if_value_is_to_short() {
String value = "AB";
InvariantException exception = assertThrows(
InvariantException.class,
() -> new Name(value));
assertEquals(
"Value(s) of Name is not valid: Name (" + value + ") should be longer than 3.",
exception.getMessage());
}
@Test
void should_throw_invariant_exception_if_value_is_to_long() {
String value = "ABCDEFGHIJKLMNOPQRSTU";
InvariantException exception = assertThrows(
InvariantException.class,
() -> new Name(value));
assertEquals(
"Value(s) of Name is not valid: Name (" + value + ") should not be longer than 20.",
exception.getMessage());
}
}
}
The abstract ComposedValueObject
, Aggregate
and Entity
classes allow expressive definitions with some helpful methods for validation.
Have a look, e.g. at the Person
example.
Providing methods for null-validation (validateNotNull
) and adding custom validations (addInvariantViolation
) to the list of violations, which could be evaluated (evaluateValidations
).
All available releases can be viewed in the release overview.
Do you want to contribute to our open source project? Read the Contribution Guidelines and get started 🙂
If you have any questions or ideas feel free to create an issue.
This open source project is being developed by Novatec Consulting GmbH with the support of the open source community.