I always used setters as a place to validate a value before assigning it to a field.
public class Person {
private int id;
public int getId() {
return this.id;
}
public int setId(int id) {
if (id < 0) {
throw new IllegalArgumentException("id must be positive.");
}
this.id = id;
}
public Person(int id) {
setId(id);
}
}
What I think is good about it is that I now have one place where a value gets validated before assignment and I can call it from everywhere. But the compiler warns me about that overridable method call in the constructor of the class. I read What's wrong with overridable method calls in constructors? and understand the issues this might cause and that it is recommended to use a Builder Pattern instead. But would it be also okay to just add final to the getters and setters instead to prevent overriding those properties?