Skip to content

Validate receiver object properties to shorten the codeΒ #71

Open
@ydanneg

Description

Problem

Currently we have to provide references to a class properties to validate like that

data class LongLongLongClassNameEmployee(val id: Int, val name: String, val email: String) {
    init {
        validate(this) {
            validate(LongLongLongClassNameEmployee::id).isPositive()
            validate(LongLongLongClassNameEmployee::name).hasSize(min = 3, max = 80)
            validate(LongLongLongClassNameEmployee::email).isNotBlank().isEmail()
        }
    }
}
  • It becomes very annoying when class names are long.
  • It is also confusing and questionable: why we have to provide type if we already work with an instance of this class provided through validate(this)?

The problem is that we can't currently provide property references like that:

data class LongLongLongClassNameEmployee(val id: Int, val name: String, val email: String) {
    init {
        validate(this) { employee ->
            validate(employee::id).isPositive()
            validate(employee::name).hasSize(min = 3, max = 80)
            validate(employee::email).isNotBlank().isEmail()
        }
    }
}

or even like this:

data class LongLongLongClassNameEmployee(val id: Int, val name: String, val email: String) {
    init {
        validate(this) {
            validate(it::id).isPositive()
            validate(it::name).hasSize(min = 3, max = 80)
            validate(it::email).isNotBlank().isEmail()
        }
    }
}

This is due to a limitation of Validator implementation that works only with KProperty1 property types of a Kotlin Reflect package.

When we reference class property Kotlin returns KProperty1 type which is now used in Validator implementation.
When we reference class instance property Kotlin returns KProperty0 type which is not supported by Validator implementation.

Possible solution

Validator could work with both KProperty0 and KProperty1 types (by overloading validate functions) that will give us the way to get property from a validation receiver directly

Suggested working test:

@Test
    fun `should validate by KProperty0`() {
        validate(Employee(company = Company(1))) {
            validate(it::company).isNotNull().validate { company ->
                validate(company::id).isNotNull()
            }
            validate(it::id).isNull()
            validate(it::address).isNull()
            validate(it::name).isNull()
        }
    }

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions