Class Validator<T>


  • public class Validator<T>
    extends Object
    A class that validates arguments of a specified generic type. Given a validation function that emits an error message if and only if the validation fails, this object's validate method will return the original valid argument, or throw an IllegalArgumentException with the custom error message if it fails to validate.
    • Constructor Detail

      • Validator

        public Validator​(Function<T,​Optional<String>> validateFunction)
        Constructor to build a validator given the mapping function that validates. If the argument is valid, the mapping function should return an empty Optional. Otherwise, it should return an Optional containing the error message to be set in the IllegalArgumentException.
        Parameters:
        validateFunction - the function that validates or returns an error message
    • Method Detail

      • validate

        public final T validate​(T argument)
        Validates the provided argument.
        Parameters:
        argument - argument to validate
        Returns:
        the argument, if validation passes
        Throws:
        IllegalArgumentException - if validation fails
      • and

        public final Validator<T> and​(Validator<T> other)
        Creates a new validator that is the conjunction of this one and the given one. An argument passed to the returned validator is valid if only if it passes both validators. If the other validator is null, the current validator is returned unchanged.
        Parameters:
        other - other validator
        Returns:
        combined validator
      • or

        public final Validator<T> or​(Validator<T> other)
        Creates a new validator that is the disjunction of this one and the given one. An argument passed to the returned validator is valid if and only if it passes at least one of the validators. If the other validator is null, the current validator is returned unchanged.
        Parameters:
        other - other validator
        Returns:
        combined validator
      • not

        public final Validator<T> not()
        Creates a new validator that is the negation of this one. An argument passed to the returned validator is valid only if it fails this one.
        Returns:
        negated validator