https://kotlinlang.org logo
#announcements
Title
# announcements
e

ecampolo

11/21/2017, 10:54 AM
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

Andreas Sinz

11/21/2017, 12:59 PM
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

ecampolo

11/21/2017, 1:04 PM
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

Andreas Sinz

11/21/2017, 1:05 PM
yeah
e

ecampolo

11/21/2017, 1:07 PM
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

Andreas Sinz

11/21/2017, 1:11 PM
yeah, thats unfortunate, but you won't be able to get a vaild instance nevertheless
e

ecampolo

11/21/2017, 1:11 PM
true, but it feels ... dirty ?
a

Andreas Sinz

11/21/2017, 1:12 PM
indeed
is it necessary that email is mutable?
e

ecampolo

11/21/2017, 1:20 PM
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
4 Views