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

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • 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
  • Building a Kotlin Mobile App With the Salesforce SDK: Editing and Creating Data

Trending

  • A Complete Guide To Implementing GraphQL for Java
  • Essential Monitoring Tools, Troubleshooting Techniques, and Best Practices for Atlassian Tools Administrators
  • Linting Excellence: How Black, isort, and Ruff Elevate Python Code Quality
  • Open-Source Dapr for Spring Boot Developers
  1. DZone
  2. Coding
  3. Languages
  4. DSL Validations: The Whole Enchilada

DSL Validations: The Whole Enchilada

As a conclusion to the series where we have learned to create the building blocks for DSL-based validations, let's put it all together for a complete solution.

By 
Scott Sosna user avatar
Scott Sosna
DZone Core CORE ·
Apr. 09, 24 · Tutorial
Like (1)
Save
Tweet
Share
2.0K Views

Join the DZone community and get the full member experience.

Join For Free

This is part 4 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

In this final part of a four-part tutorial, after introducing the concept of property validators and operators, we can tie it all together by validating complete beans in a more reusable way.


PropertyBeanValidator

PropertyBeanValidator is the worker class that evaluates a collection of PropertyValidators against a target object.  The specific property validators are provided during construction and are AND'ed together as if wrapped by an AndOperator (e.g., all property validators must pass for the entire bean to validate successfully).

Kotlin
 
open class PropertyBeanValidator<T> (
  validators: Set<PropertyValidator<T>>) : DefaultBeanValidator() {

  override fun <T> validate(
    source: T,
    vararg groups: Class<*>?): Set<ConstraintViolation<T>> {
    //  Place to catch all the constraint violations that
    //  occurred during this validation
    val violations = mutableSetOf<ConstraintViolation<T>>()

    //  Call each individual validator to determine whether
    //  or not the bean validates correctly
    validators
      .parallelStream()
      .forEach { 
        it as PropertyValidator<T>; it.validate(source, violations) 
      }

    return violations
  }
}


Putting It All Together

We'll reuse the Student class defined in Part 2, "DSL Validations: Child Properties" (linked in the introduction).

Kotlin
 
data class Address(
 val line1: String?,
 val line2: String?
 val city: String,
 val state: String,
 val zipCode: String
)

data class Student(
 val studentId: String,
 val firstName: String?,
 val lastName: String?,
 val emailAddress: String?,
 val localAddress: Address
)


For this example, we have three business rules to apply against a Student object:

  • firstName and lastName must both be present or missing;
  • address.line2 presence requires that address.line1 is also present;
  • address.zipCode must be formatted correctly. 

Ad-Hoc Bean Validator

Bean validators are created by instantiating PropertyBeanValidator directly by a factory allowing callers to be provided an appropriate validator without actually knowing what needs to be validated.  The factory determines the specific validations required - based on caller, data state, feature flags, etc. - and builds the validator on the fly.

Kotlin
 
val validators = setOf(
  OrOperator(
    "studentName",
    listOf(
      AndOperator(
        "namePresent",
        listOf(
           NotBlankValidator("firstName", Student::firstName),
           NotBlankValidator("lastName", Student::lastName)
        )
      ),
      AndOperator(
        "nameNotPresent",
        listOf(
          NullOrBlankValidator("firstName", Student::firstName),
          NullOrBlankValidator("lastName", Student::lastName)
      ),
    )
    "first/last name must both be present or null"
  ),
 
  OrOperator(
    "Line2RequiresLine1",
    listOf(
      ChildPropertyValidator(
        "line1NotNull",
        Student::localAddress,
        NotBlankValidator("line1", Address::line1)),
      ChildPropertyValidator(
        "line2Null",
        Student::localAddress,
        NullOrBlankValidator("line2", Address::line2)), 
    ),
    "line2 requires line1." 
  ),

  ChildPropertyValidator(
    "address.zipCode",
    Student::localAddress,
    ZipCodeFormatValidator("address", Address::zipCode)
  )
)

val validator = PropertyBeanValidator(validators)


Class-Specific Bean Validator

A class-specific validator is useful when there is one and only one way to validate a class and consistent and correct usage across the code base.  Here we extend PropertyBeanValidator and pass in the validators via an alternative constructor.

Kotlin
 
class StudentBeanValidator (validators: Set<PropertyValidator<Student>>)
  : PropertyBeanValidator<Student> (validators) {

  constructor() : this(getValidators())

  companion object {
    fun getValidators() : Set<PropertyValidator<Student>> {
      return setOf(
        .
        .
        <same validations as above>
        .
        .
      )
    }
  }
}


NOTE: It's a little more awkward in Kotlin, as you can't access data in the companion object before the object is constructed, but calling a method is allowed. Statics in Java would allow the creation of an immutable set that could be used for any number of instantiations.

Validating

Kotlin
 
// Assume the student is created from a database entry
val myStudent = retrieveStudent("studentId")

// Validate the object
val violations = mutableSetOf<ConstraintViolation<T>>()
validator.validate(myStudent, violations)

// empty collection means successful validation
val successfullyValidated = violations.isEmpty()


Annotation-Based Validation

Jakarta's validation interface ConstraintValidator declares an annotation-driven validation which, in turn, can be defined via the DSL.

First, implement the annotation that can be applied for validating students, in this example, limited to method parameters.

Kotlin
 
@Constraint(validatedBy = [StudentValidator::class])
@Target(AnnotationTarget.VALUE_PARAMETER)
@Retention(AnnotationRetention.RUNTIME)
annotation class ValidStudent(
  val message: String = "Invalid Student record",
  val groups: Array<KClass<*>> = [],
  val payload: Array<KClass<out Payload>> = []
)


Next, implement the class-extending ConstraintValidator that does the actual validation, using the StudentBeanValidation implemented earlier.

Kotlin
 
class StudentValidator : ConstraintValidator<ValidStudent, Student> {
  override fun isValid(student: Student, 
                       context: ConstraintValidatorContext): Boolean {
    val errors = StudentBeanValidator().validate(student)
    return if (errors.isNotEmpty()) {
      context.disableDefaultConstraintViolation()
      context.buildConstraintViolationWithTemplate(
          "Student validation failed with following errors :$errors")
        .addConstraintViolation()
          false
       } else {
         true
       }
    }
  }
}


Here is the annotation in action:

Kotlin
 
fun registerStudentForClass(@ValidStudent student: Student): Student {
   .
   .
   <do some work>
   .
   .
}


For those interested, this Baeldung tutorial dives deeper into validations than what I've covered.

Final Thoughts

DSL Validations is a language-independent way of checking for bean/object validity without writing ever more if-then-else statements that are uncommented, unclear, and unreadable, and are easy to extend and customize for whatever specific requirements your organization has.

Supporting Code

DefaultBeanValidator

Kotlin
 
open class DefaultBeanValidator : Validator {
  override fun <T> validate(source: T,
                            vararg groups: Class<*>?)
  : Set<ConstraintViolation<T>> {
    throw UnsupportedOperationException (EXCEPTION_MESSAGE)
  }

  override fun <T> validateProperty(source: T,
                                    propertyName: String?,
                                    vararg groups: Class<*>?)
  : Set<ConstraintViolation<T>> {
    throw UnsupportedOperationException (EXCEPTION_MESSAGE)
  }

  override fun <T> validateValue(beanType: Class<T>?,
                                 propertyName: String?,
                                 value: Any?, vararg groups: Class<*>?)
  : Set<ConstraintViolation<T>> {
    throw UnsupportedOperationException (EXCEPTION_MESSAGE)
  }

  override fun getConstraintsForClass(clazz: Class<*>?): BeanDescriptor {
    throw UnsupportedOperationException (EXCEPTION_MESSAGE)
  }

  override fun <T : Any?> unwrap(type: Class<T>?): T {
    throw UnsupportedOperationException (EXCEPTION_MESSAGE)
  }

  override fun forExecutables(): ExecutableValidator {
    throw UnsupportedOperationException (EXCEPTION_MESSAGE)
  }

  companion object {
    const val EXCEPTION_MESSAGE = "Not yet implemented"
  }
}


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

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

Opinions expressed by DZone contributors are their own.

Related

  • 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
  • Building a Kotlin Mobile App With the Salesforce SDK: Editing and Creating Data

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send 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: