DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Angular RxJS Unleashed: Supercharge Your App With Reactive Operators
  • Programming Solutions for Graph and Data Structure Problems With Implementation Examples (Word Dictionary)
  • Testcontainers With Kotlin and Spring Data R2DBC
  • Rust’s Ownership and Borrowing Enforce Memory Safety

Trending

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Spring and PersistenceContextType.EXTENDED
  • Contextual AI Integration for Agile Product Teams
  • Navigating the LLM Landscape: A Comparative Analysis of Leading Large Language Models
  1. DZone
  2. Data Engineering
  3. Data
  4. DSL Validations: Operators

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.

By 
Scott Sosna user avatar
Scott Sosna
DZone Core CORE ·
Apr. 02, 24 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
1.1K Views

Join the DZone community and get the full member experience.

Join For Free

This 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.

Kotlin
 
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 the ConstraintViolation; 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.

Kotlin
 
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.

Kotlin
 
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.

Kotlin
 
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

Kotlin
 
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

Kotlin
 
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

Kotlin (programming language) Operator (extension) Domain-Specific Language Data (computing)

Published at DZone with permission of Scott Sosna. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Angular RxJS Unleashed: Supercharge Your App With Reactive Operators
  • Programming Solutions for Graph and Data Structure Problems With Implementation Examples (Word Dictionary)
  • Testcontainers With Kotlin and Spring Data R2DBC
  • Rust’s Ownership and Borrowing Enforce Memory Safety

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!