ijp
04/21/2017, 10:29 AMpublic 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:
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:
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?