Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation and DDD - kotlin data classes

In Java I would do validation when creating constructor in domain object, but when using data class from kotlin I don't know how to make similar validation. I could do that in application service, but I want to stick to domain object and it's logic. It's better to show on example.

public class Example {

    private String name;

    Example(String name) {
        validateName(name);
        this.name = name;
    }
}

In Kotlin I have just a data class is there a way to do it similarly to Java style?

data class Example(val name: String)
like image 705
Surrealistic Avatar asked Aug 30 '18 09:08

Surrealistic


1 Answers

You can put your validation code inside an initializer block. This will execute regardless of whether the object was instantiated via the primary constructor or via the copy method.

data class Example(val name: String) {
    init {
        require(name.isNotBlank()) { "Name is blank" }
    }
}

A simple example:

fun main() {
    println(Example(name = "Alice"))
    println(try { Example(name = "") } catch (e: Exception) { e })
    println(try { Example(name = "Bob").copy(name = "")  } catch (e: Exception) { e })
}

Produces:

Example(name=Alice)
java.lang.IllegalArgumentException: Name is blank
java.lang.IllegalArgumentException: Name is blank
like image 78
Adam Millerchip Avatar answered Oct 24 '22 10:10

Adam Millerchip