【发布时间】:2013-10-23 12:30:06
【问题描述】:
因此,举个例子,假设我们有一个名为Question 的abstract class,该问题包含很多字符串,一个用于问题本身,一个用于答案,两个响应发布给用户,如果他的问题是对的/错的。
public abstract class Question {
private final String question;
private final String answer;
private final String answerCorrect;
private final String answerWrong;
}
我的问题基本上是,初始化所有字符串的常用方法是什么?到目前为止,我已经编写了 2 个关于如何做到这一点的版本,它们各有优缺点,我想知道是否有某种“最佳编码实践”。
A 版
初始化构造函数中的所有内容。
public abstract class Question {
//...
public Question(String question, String answer, String answerCorrect, String answerWrong) {
this.question = question;
this.answer = answer;
this.answerCorrect = answerCorrect;
this.answerWrong = answerWrong;
}
}
这似乎很方便,我唯一的问题是用户无法确定字符串的顺序。
public class ExampleClass extends Question {
public ExampleClass() {
super("I think, that's the answer", "and that's the question", "answer wrong?", "answer right?");
}
}
版本 B
不要立即初始化并等待用户执行。
public abstract class Question {
//...
public Question() {
this.question = "";
this.answer = "";
this.answerCorrect = "";
this.answerWrong = "";
}
public void setQuestion(String question) {
this.question = question;
}
//...
}
这使得初始化变量更容易,但是字符串不能再是final,并且不能保证用户会初始化所有的变量。
我也想过让子类实现在Question 的构造函数中调用的抽象方法来初始化所有字符串并保留它们final,但那个版本对我来说似乎有点太奇怪了.
还有其他/更好的方法吗?我应该更喜欢哪个版本?
提前感谢您的支持。
【问题讨论】:
-
如果你的属性是
final并且你放了setter,你的代码将不会编译 -
@nachokk 我提到了它:“(...)字符串不能再是最终的(...)”
-
the only problem I have with this is that users will not be sure, in which order the strings have to be。用户不会调用构造函数,开发人员会这样做。为了确保正确的顺序,您应该写评论。这不应该妨碍您选择版本 A。 -
考虑到大多数 IDE 都有弹出窗口,可以为您提供构造函数的参数,第一个缺点是 N/A(另请注意,这个“缺点”适用于几乎所有编写过的方法和构造函数) .
-
如果你有一个额外的non-final成员“points”,那么使用CTOR给它一个合理的“undefined”值。然后为它添加一个setter。在 getter 的文档中,该“未定义”值是什么。就像“-1 如果还没有设置点”。
标签: java initialization abstract-class