最适合的边界检查的地方 - 构造函数或setter? [英] Most appropriate place for bounds checking - constructor or setter?
问题描述
还是比较新的Java和我想知道是更好的方式来处理这个。我有一个类构造函数,它接受几个参数,在这个类中还有public getters和setter:
Still relatively new to Java and I'm wondering which is the better way to handle this. I have a class constructor that takes a few parameters, and also in this class are public getters and setters:
private String name;
private Float value;
public MySampleClass(String theName, Float theValue) {
setName(theName);
setValue(theValue);
}
public void setName(String n) {
this.name = n;
}
public value setValue(Float v) {
this.value = v;
}
我想对这个Float做一些边界检查。它似乎是最好的地方,它将在安装程序:
I'd like to do some bounds checking on this Float. It seems like the best place to put it would be in the setter:
public value setValue(Float v) {
if (v < 0.0f) {
this.value = 0.0f;
} else if (v > 1.0f) {
this.value = 1.0f;
}
}
此代码最初在构造函数中检查了边界,再次在安装者,这似乎多余。我改变了构造函数来调用setter并把check放在那里。这是更有意义吗?
This code originally had the bounds checking in the constructor and again in the setter, which seemed redundant. I changed the constructor to call the setter and put the checks in there. Does that make more sense? Or am I violating some convention of which I am completely unaware?
推荐答案
从构造函数调用可覆盖的方法是一个坏主意。做更像这样的事情:
Calling overridable methods from your constructor is a bad idea. Do something more like this:
private String name;
private Float value;
public MySampleClass(String theName, Float theValue) {
this.name = theName;
setValueImpl(theValue);
}
public void setName(String n) {
this.name = n;
}
public void setValue(Float v) {
setValueImpl(v);
}
private void setValueImpl(Float v) {
if (v < 0.0f) {
this.value = 0.0f;
} else if (v > 1.0f) {
this.value = 1.0f;
}
}
这样可以在两个地方验证,调用overridable方法。有关详情,请参见此问题。
This gives you the validation in both places and eliminates the calls to overridable methods. See this question for more on this.
编辑:如果您打算对子类化 MySampleClass
并希望验证设置器可用,请声明 protected final
而不是 private
。
If you plan on subclassing MySampleClass
and want the validation setter available, declare it protected final
instead of private
.
这篇关于最适合的边界检查的地方 - 构造函数或setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!