Reputation: 1621
I've been told to use setters to change properties of a object and to have setters validate the data the property is being set to. I've also been told to not use setters in constructors due to subclass overriding. How should you go about validating the arguments of a constructor while allowing your setters to be overridden? Should you repeat the validation code?
With setters:
public class A {
private int x;
public A(int x){
setX(x);
}
public void setX(int x) {
if (x > 6)
this.x = x;
else
this.x = 7;
}
}
Without setters:
public class A {
private int x;
public A(int x){
this.x = x;
}
public void setX(int x) {
if (x > 6)
this.x = x;
else
this.x = 7;
}
}
Without setters and doubled code:
public class A {
private int x;
public A(int x){
if (x > 6)
this.x = x;
else
this.x = 7;
}
public void setX(int x) {
if (x > 6)
this.x = x;
else
this.x = 7;
}
}
Upvotes: 1
Views: 114
Reputation: 1084
One option is that you write a private method that is used in the setter and in the constructor so you haven't doubled code and the subclasses could overide the setter easily. This is my way of doing it.
If you aren't allowed to do that, you have to use doubled code.
---- EDIT: ----
This is only suitable for long checks or if no default value should be set.
public class A {
private int x;
public A(int x){
if(checkX())
this.x=x;
else
this.x = 7;
}
public void setX(int x) {
if (checkX(x))
this.x = x;
else
this.x = 7;
}
private boolean checkX(int x) {
if (x > 6)
return true;
else
retrun false;
}
}
Upvotes: 1