So, just as an example, let's say we have an abstract class
called Question
, that question contains a lot of strings, one for the question itself, one for the answer and two responses posted to the user, if he got the question right / wrong.
public abstract class Question {
private final String question;
private final String answer;
private final String answerCorrect;
private final String answerWrong;
}
My question basically is, what would be a common way to initialize all of the strings? So far I've made up 2 versions on how to do it, they have their up- and downsides and I wanted to know, if there was some kind of "best coding practice" for this.
Version A
Initialize everything in the constructor.
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;
}
}
This seems pretty convenient, the only problem I have with this is that users will not be sure, in which order the strings have to be.
public class ExampleClass extends Question {
public ExampleClass() {
super("I think, that's the answer", "and that's the question", "answer wrong?", "answer right?");
}
}
Version B
Don't initialize instantly and wait for the user to do it.
public abstract class Question {
//...
public Question() {
this.question = "";
this.answer = "";
this.answerCorrect = "";
this.answerWrong = "";
}
public void setQuestion(String question) {
this.question = question;
}
//...
}
This makes it easier to initialize variables, but the Strings can't be final
anymore and it's not guaranteed that the user will initialize all of them.
I've also thought about letting the child-class implement abstract methods that are called in the constructor of Question
to initialize all the strings and to keep them final
, but that version seemed a little too strange to me.
Are there other / better ways to do it? What version should I prefer?
Thanks in advance for your support.