I wonder how I can validate an entity in its prope...
# announcements
e
I wonder how I can validate an entity in its properties both via constructor and setter without duplicating code. More formally, how do you get around with aggregate invariants (DDD). For example:
Copy code
class Person(email: String) {
    var email: String = email
    set(value) {
        require(value.trim().isNotEmpty(), { "The email cannot be blank" })
        field = value
    }

    init {
        require(email.trim().isNotEmpty(), { "The email cannot be blank" })
    }
}
I tried with Delegation but feels a little bit complex since I would need to have NotEmptyString , NotEmptyCollection, or any kind of validation. Also I want to avoid those extra objects per property.
a
Copy code
class Person(_email: String) {
    var email: String = email
    set(value) {
        require(value.trim().isNotEmpty(), { "The email cannot be blank" })
        field = value
    }

    init {
        email = _email
    }
}
Just assign the value of the constructor-argument to your
email
-property?
e
do you mean?:
Copy code
class Person(email: String) {
    var email: String = email
        set(value) {
            require(value.trim().isNotEmpty(), { "The email cannot be blank" })
            field = value
        }

    init {
        this.email = email
    }
}
a
yeah
e
haha i tried so many variants that I cannot tell what was the issue with that .. but, it seems like it is want I want., i ll try it to see if I am missing something., thank you Andreas 😉
dont I reassigning the variable twice ?
i think thats the issue
if I do
Copy code
Person(email = "")
, the object is first initialized with an empty value and then executing the init block calling the setter, resulting in an exception
a
yeah, thats unfortunate, but you won't be able to get a vaild instance nevertheless
e
true, but it feels ... dirty ?
a
indeed
is it necessary that email is mutable?
e
no, but it is an example, assume that it is., like having an age field whose value should be positive
maybe an Employee class with role, job, area, etc
the underlying problem is how to deal with validation both while constructing the object and then, if a need to update one of its values