DSL Validations: Operators
Now that we have seen how the DSL validates individual properties, the next step is to combine individual property validations into larger, more complex conditionals.
Join the DZone community and get the full member experience.
Join For FreeThis is part 3 of a 4-part tutorial
- Part 1: DSL Validations: Properties
- Part 2: DSL Validations: Child Properties
- Part 3: DSL Validations: Operators
- Part 4: DSL Validations: The Whole Enchilada
Operators provide a value for validating properties as a single unit: think of a multi-part conditional check in an if statement. The most obvious operators are logical AND (&&
) and OR (!!
), though other operators are possible.
Implementing Operators
Operators are themselves validators, implementing the same fun validate(): Boolean
as property validators but instead evaluates one or more validators to determine overall success or failure, e.g. all pass validations for AND or at least one passes validation for OR.
AbstractOperator
Each implemented operator extends AbstractOperator
to ensure correct equals
and hashCode
methods exist, similar to AbstractPropertyValidator
. Instead of a getter
provided during construction, an operator is provided a collection of PropertyOperatorValidator
's against which the operator is applied.
abstract class AbstractOperator<S> (
protected val conditionName: String,
protected val validators: List<PropertyOperatorValidator<S>>) :
AbstractValidator<S>() {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AbstractOperatorValidator<*>
if (conditionName != other.conditionName) return false
return true
}
override fun hashCode(): Int {
return Objects.hash(conditionName)
}
}
Property validators and operators both implement PropertyOperatorValidator
via AbstractValidator
which allows an operator to recursively evaluate operators, similar to using parentheses to define sub-conditions within in the overall conditional.
AndOperator
/OrOperator
Logical operators are constructed with the following parameters
conditionName
: descriptive name of the operator's purpose or intent;validators
: a collection of validators that are evaluated by the operator;errorMessage
: the error message provided in theConstraintViolation
; otherwise, constraint violations are created for each validator evaluated.
An operator-specific error message often provides better context than individual messages for each failed condition, such as Both first and last names required. instead of firstName
required; lastName
required.
class AndOperator<S>(conditionName: String,
validators: List<PropertyValidator<S>>,
val errorMessage: String? = null) :
AbstractOperator<S>(conditionName, validators) {
override fun validate(
source: S,
errors: MutableSet<ConstraintViolation<S>>): Boolean {
val errorsToUse =
if (errorMessage.isNullOrBlank())
errors
else
mutableSetOf()
val success = validators.all {
it.validate(source, errorsToUse)
}
if (!success && !errorMessage.isNullOrBlank()) {
addViolation(
source,
errorMessage,
errorMessage,
conditionName,
null,
errors)
}
return success
}
}
The only change required to implement OrOperator
is that only one validator must pass validation.
val success = validators.any {
it.validate(source, errorsToUse)
}
Putting It All Together
For example, in social planning, an Invitee
is the person being invited. The state of an invitee is INVITED
, ACCEPTED
, or DECLINED
.
data class Invitee {
val state: InviteeState,
val firstName: String?,
val lastName: String?,
val emailAddress: String,
val howMany: Int?
}
When accepting or declining the invitation, the user provides her name. For accepted invitations, she indicates how many people are attending (e.g., the invitee herself, partner or spouse, children, friends, etc.). Otherwise, the optional properties are not required.
General Programing Implementation
val invitee = getInvitee(...)
if (invitee.state == InviteeState.INVITED) return true
if (invite.firstName.isNullOrBlank() || invite.lastName.isNullOrBlank()) {
log.warn("First and last name required.")
return false
}
if (invitee.state == InviteeState.ACCEPTED && howMany :? 0 <= 0) {
log.warn("Must specify how many people expected to attend.")
return false
}
return true
Domain-Specific Language Solution
val invitee = getInvitee(...)
// howMany required when invitation accepted
val accepted = OrOperator(
conditionName = "acceptedHowMany",
errorMessage = "Must specify number of attendees when accepting.",
validators = setOf(
EnumNotEqualsValidator(
propertyName = "state",
getter = Invitee::stage,
value = InviteeState.ACCEPTED),
PositiveIntegerValidator(
propertyName = "howMany",
getter = Invitee::howMany)
)
)
// Invitee must provide first/last name when accepting/declining invite
val responded = OrOperator(
conditionName = "inviteReply",
errorMessage = "First and last name required when accepted/declined.",
validators = setOf(
EnumNotEqualsValidator(
propertyName = "state",
getter = Invitee::stage,
value = InviteeState.INVITED
),
AndOperator (
conditionName = "allPresent",
errorMessage = null,
validators = setOf(
StringNotBlankValidator("firstName", Invitee::firstName),
StringNotBlankValidator("lastName", Invitee::lastName),
)
)
)
)
// Both of the above must be true
val operator = AndOperator (
propertyName = "inviteeValidation",
validators = setOf (accepted, responded)
)
// Validate the complete operator
val violations = mutableSetOf<ConstraintViolation<T>>()
operator.validate(invitee, violations)
// empty collection means successful validation
val successfullyValidated = violations.isEmpty()
Comparison
Though the general implementation is shorter, is it a better implementation? Some advantages of validating via the DSL are:
- Correctness: Validator names (should) clearly identify how the property is being validated. The actual validation is implemented once for all usages rather than implemented ad-hoc, reducing test coverage. Operator error messages provide context to the business requirement and use case. No opportunity to inject side-effects into the validation.
- Consistency: The implementation is the implementation, with no differences wherever a specific validation is needed: if Apache Common LangStringUtils is used once, it's Apache Common Lang StringUtils used always; Avoids inconsistencies and bugs caused by using similar libraries in different parts of the code base.
- Reusability: Define once, use many: create the validation in a common library that can be accessed when required; Preferred over cut-and-paste, duplicated implementations, or forcing into an awkward class hierarchy to provide common access.
- Readability: Almost language agnostic, the validation is understood by understanding how the DSL is created, not how the code is written; Requires less understanding of any specific JVM programming language, borderline self-documenting.
- Ad-Hoc: Just-in-time validations created programmatically without the complexities of bytecode manipulation via ASM or something similar.
Final Comments
DSL operators allow us to implement more complex and useful validators, much beyond what is possible with property-level annotations/validators (e.g., @NotBlank
, @NotNull
, @Email
, etc). The final step is to wrap this with a true Jakarta Bean Validator
that can be used to validate a complete bean.
Image © 1991 Scott C Sosna
Published at DZone with permission of Scott Sosna. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments