jeudi 25 janvier 2018

Answer object and Object Oriented Design

I have doubts about this design:

public abstract class Answer {

    private long id;

    private Question question;

    public Answer(Question question) {
        this.question = question;
    }

   abstract List<String> getAnswers(){
   }
}

And subclassed:

public class SingleAnswer extends Answer {
    private String answer;

    public SingleAnswer(Question question) {
        super(question);
    }

    public List<String> getAnswer() {
        return Collections.singletonList(answer);
    }

   public void setAnswers(Set<String> answers) {
        if(answers.size()!=1)
            throw new IllegalArgumentException("You have to provide only one answer");
        this.answers = answers;
    }

}


public class MultiAnswer extends Answer{
    private List<String> answers;

    public MultiAnswer(Question question) {
        super(question);
    }

    public List<String> getAnswers() {
        return answers;
    }

    public void setAnswers(Set<String> answers) {
        if(answers.isEmpty())
            throw new IllegalArgumentException("You have to provide at least one answer");
        this.answers = answers;
    }
}

MultiAnswer object can have more than one answer (like checkbox) and SingleAnswer object can have only single answer (like answer for open question, or single choice a,b,c,d question).

Now, I want get list of Answer objects and find out what answers they have and use them for some comparison. I make abstract method List getAnswers() for thast purpose but I have doubts if this is a good design, because SingleAnswer can hold only one value/answer and signature of method getAnswers indicated that SingleAnswer can return more than one answer.

Is it good solution or can it be solved in different way?

Aucun commentaire:

Enregistrer un commentaire