Hi everyone. When constructing classes, I often ti...
# getting-started
i
Hi everyone. When constructing classes, I often times have certain validation checks on parameters, for eg certain Strings may not be empty, or certain values need to be > 0 etc. These validation checks typically need to be enforced on construction and whenever fields are updated. In Java I would do the following:
Copy code
public class Person {
    
    private String name;

    public Person(String name) {
        setName(name);
    }
    
    public void setName(String name){
        if(name.isEmpty())
            throw new IllegalArgumentException("Empty name");
        this.name = name;
    }
}
Since the property initialiser in Kotlin does not call the setter, it seems as if I have two choices to achieve the same result. Option 1:
Copy code
class Person(name: String){
    var name: String = ""
    set(value) = if(!name.isEmpty()) field = value else throw IllegalArgumentException("Empty name")

    init {
        this.name = name
    }

}
Option two:
Copy code
class Person(name: String){
    var name: String = if(!name.isEmpty()) name else throw IllegalArgumentException("Empty name")
    set(value) = if(!name.isEmpty()) field = value else throw IllegalArgumentException("Empty name")
}
I’m not a big fan of either of these. Option one feels like a double initialisation, whereas Option two feels like duplication of business logic. Seeing that this is a common pattern in my code, I was wondering if there are any other options that I could use for this scenario?