Validating Arguments

YAVI supports validating arguments of a constructor or factory method before creating an object with Arguments Validator.

This is one of YAVI's unique features.

Arguments Validator, as the name implies, is a Validator for arguments.

A normal Validator, like Bean Validation, validates if the values are valid for the object to which the values are set, while the Arguments Validator validates that the arguments set to the Object are valid.

Since an object is created before validation in a normal Validator, there is a possibility of creating an object in an incomplete state temporarily. For example, even if the constraint of notNull() is imposed on the Validator side, if the null check is implemented in the constructor, this null check will work before the validation by Validator is executed.

The Arguments Validator creates an object after validation, so you don't have to worry about an incomplete object. The Always Valid model shows how to combine this with a private constructor or a record to make invalid objects impossible to create.

Defining an arguments validator

Use am.ik.yavi.validator.Yavi#arguments() to build an arguments validator. Each _xxx method adds one argument with its name and constraints, and apply creates the validator:

import am.ik.yavi.arguments.Arguments3Validator;
import am.ik.yavi.core.Validated;
import am.ik.yavi.validator.Yavi;

public class Person {

    public static final Arguments3Validator<String, String, Integer, Person> validator = Yavi.arguments()
        ._string("name", c -> c.notBlank().lessThanOrEqual(100)) // Constraint on the first argument of Person::new
        ._string("email", c -> c.notBlank().lessThanOrEqual(100).email()) // Constraint on the second argument of Person::new
        ._integer("age", c -> c.greaterThanOrEqual(0).lessThan(200)) // Constraint on the third argument of Person::new
        .apply(Person::new);

    // ...
}

The Arguments Validator can be used as follows:

Validated<Person> personValidated = Person.validator.validate("John Doe", "jdoe@example.com", 30);

The program below builds the same arguments validator for a class whose only constructor is private, so a Person can be created only through Validated. It prints the violations of an invalid call and the object created by a valid one. Press Run to compile and execute it in your browser; the output appears below the cell.

am.ik.yavi.arguments.Arguments1Validator to am.ik.yavi.arguments.Arguments16Validator are available. The maximum number of arguments is 16.

Available argument kinds

The following argument kinds are available, each with a constraint type for that kind:

  • _string
  • _boolean
  • _short, _integer, _long, _float, _double
  • _bigInteger, _bigDecimal
  • _localDate, _localTime, _localDateTime, _offsetDateTime, _instant, _year, _yearMonth, _zonedDateTime
  • _enum
  • _object

_object accepts any reference type, including arrays, collections and maps:

Arguments1Validator<LocalDate, LocalDate> dateValidator = Yavi.arguments()
    ._localDate("date", c -> c.notNull())
    .apply(date -> date);

Arguments1ValidatorBuilder<Color, Color> colorValidatorBuilder = Yavi.arguments()
    ._enum("color", c -> c.notNull());
Arguments1Validator<Color, Color> colorValidator = colorValidatorBuilder.apply(color -> color);

Arguments1Validator<List<String>, List<String>> tagsValidator = Yavi.arguments()
    ._object(ObjectValidatorBuilder.<List<String>>of("tags", c -> c.notNull()).build())
    .apply(tags -> tags);

_collection, _map and _objectArray are not argument kinds; they are ValidatorBuilder methods for validating a collection, map or array property of an object. See Using YAVI for details.

Validating method arguments

Arguments Validator can be used for validating method arguments as well.

// From https://beanvalidation.org/
public class UserService {
    public User createUser(/* @Email */ String email,
                           /* @NotNull */ String name) {
        // ...
    }
}

The arguments for UserService.createUser in the above example can be validated with ArgumentsValidatorBuilder:

Arguments3Validator<UserService, String, String, User> validator = ArgumentsValidatorBuilder
    .of(UserService::createUser)
    .builder(b -> b
        ._object(Arguments3::arg1, "userService", c -> c.notNull())
        ._string(Arguments3::arg2, "email", c -> c.email())
        ._string(Arguments3::arg3, "name", c -> c.notBlank()))
    .build();

UserService userService = new UserService();
Validated<User> userValidated = validator.validate(userService, "jdoe@example.com", "John Doe");

Use this form when the values come from an instance method reference, because the receiver is validated as the first argument. It is also the form generated by the annotation processor meta constants described in Annotation Processor. The _xxx methods of the builder take the accessor for the argument position (Arguments3::arg1 etc.) instead of just a name; Arguments1Validator..Arguments16Validator do not inherit from each other, so use the accessor that matches the arity of the builder.

Note

void cannot be used as return type while java.lang.Void is available.

Defining a Validator for a single value

If you just want to define Arguments1Validator for a single String or Integer etc, you can write:

StringValidator<String> nameValidator = StringValidatorBuilder
    .of("name", c -> c.notBlank().lessThanOrEqual(100))
    .build();

IntegerValidator<Integer> ageValidator = IntegerValidatorBuilder
    .of("age", c -> c.greaterThanOrEqual(0).lessThan(200))
    .build();

Validated<String> nameValidated = nameValidator.validate("John Doe");
Validated<Integer> ageValidated = ageValidator.validate(30);

build(Function) converts the validated value into a Value Object:

StringValidator<Name> nameValidator = StringValidatorBuilder
    .of("name", c -> c.notBlank().lessThanOrEqual(100))
    .build(Name::new);

StringValidator<Email> emailValidator = StringValidatorBuilder
    .of("email", c -> c.notBlank().lessThanOrEqual(100).email())
    .build(Email::new);

IntegerValidator<Age> ageValidator = IntegerValidatorBuilder
    .of("age", c -> c.greaterThanOrEqual(0).lessThan(200))
    .build(Age::new);

You can also map an existing validator with map(Function):

StringValidator<Name> nameValidator = StringValidatorBuilder
    .of("name", c -> c.notBlank().lessThanOrEqual(100))
    .build()
    .map(Name::new);

andThen(Function) produces the same result and is deprecated since 0.17.0 in favor of map(Function). andThen(ValueValidator) is not deprecated; it chains another validator on the produced value:

ObjectValidator<Name, Name> nonNullNameValidator = ObjectValidatorBuilder
    .<Name>of("name", c -> c.notNull())
    .build();

Arguments1Validator<String, Name> checkedNameValidator = nameValidator
    .andThen(nonNullNameValidator);

Composing and adapting validators

compose(Function) converts the source object before validation:

Arguments1Validator<Integer, Name> nameFromIdValidator = nameValidator.compose(Object::toString);

wrap() turns an arguments validator into one that validates an ArgumentsN container, and Arguments1Validator.unwrap(...) (or ArgumentsNValidator.unwrap(...)) turns it back:

Arguments1Validator<Arguments1<String>, Name> wrappedValidator = nameValidator.wrap();
Arguments1Validator<String, Name> unwrappedValidator = Arguments1Validator.unwrap(wrappedValidator);

lazy() returns a validator that produces a Supplier of the validated value. The value is created only when the supplier is used, which lets you validate arguments inside a constructor without recursing into the constructor:

Arguments1Validator<String, Supplier<Name>> lazyValidator = nameValidator.lazy();
Supplier<Name> nameSupplier = lazyValidator.validated("John Doe");

See The Always Valid model for the lazy() usage in a record constructor.

indexed(int) appends [index] to violation names so that violations of collection elements can be told apart:

Arguments1Validator<String, Email> indexedEmailValidator = emailValidator.indexed(0);

If you want to create an Arguments1Validator for a List, you can "lift" a Validator for the element of the list as follows:

Arguments1Validator<Iterable<String>, List<Email>> emailsValidator = emailValidator.liftList();
Validated<List<Email>> emailsValidated = emailsValidator.validate(List.of("foo@example.com", "bar@example.com"));

Arguments1Validator<Iterable<String>, Set<Email>> emailSetValidator = emailValidator.liftSet();
Arguments1Validator<Iterable<String>, List<Email>> emailCollectionValidator = emailValidator
    .liftCollection(ArrayList::new);
Arguments1Validator<Optional<String>, Optional<Email>> emailOptionalValidator = emailValidator.liftOptional();

liftList(), liftSet(), liftCollection(Supplier) and liftOptional() are available as well.

split(...) validates separate arguments with separate validators, and combine(...) validates the same input with multiple validators. ArgumentsValidators.split(...) and ArgumentsValidators.combine(...) are described in Combining validators.

ArgumentsValidators.traverseN(...) validates each element of a given collection with a validator produced by a function and collects the results. sequenceN(...) applies multiple validators to the same arguments and collects the results:

Arguments1Validator<String, List<Name>> namesValidator = ArgumentsValidators
    .traverse1(List.of("John", "Jane"), value -> nameValidator);

Arguments1Validator<String, List<String>> sequencedValidator = ArgumentsValidators
    .sequence1(List.of(nameValidator.map(Name::value), nameValidator.map(Name::value)));

These "small Validators" can be very powerful parts by using the Validator combinators described in "Combining validators".

Arguments containers

Arguments1 to Arguments16 are immutable containers of validated arguments. Use Arguments.of(...) to create one:

Arguments3<String, String, Integer> arguments = Arguments.of("John Doe", "jdoe@example.com", 30);
String name = arguments.arg1();
String email = arguments.arg2();
Integer age = arguments.arg3();

argN() returns the argument at position N. firstN() and lastN() return the leading or trailing N arguments as a new container, and append, prepend and reverse return a modified copy:

Arguments1<String> first = arguments.first1();
Arguments2<String, String> firstTwo = arguments.first2();
Arguments1<Integer> last = arguments.last1();
Arguments2<String, Integer> lastTwo = arguments.last2();

Arguments4<String, String, Integer, String> appended = arguments.append("extra");
Arguments4<String, String, String, Integer> prepended = arguments.prepend("extra");
Arguments3<Integer, String, String> reversed = arguments.reverse();

equals and hashCode are implemented for the contents of the container. Arguments is final, and ArgumentsN does not inherit from ArgumentsM; the concrete container class is part of the equality check.