I am making a class called Question . This class has answers, so I want to be able to return a list of the answers that come with it.
However, if the user makes changes to the response, I want the user to call the update method so that I can perform additional checks, etc. Right now, if the user gets a list of answers, he can still change the answer by saying question.getAnswers().get(0).setDescription("BLAH BLAH").
So, I thought about returning a copy of each answer, and let the user change this and he will have to merge / update it to the question. With this approach, I can guarantee that the answer is valid, but the equals method of the response is based on the description and correct field, and not in the id field, because I use JPA. If the user modifies the answer using this approach, the update method will not find the answer because the description field has changed and it is no longer equal, so it does not find it in the list.
Any tips?
public void updateAnswer(Answer answer) { int index = answers.indexOf(answer); answers.set(index, answer); } public List<Answer> getAnswers() { return Collections.unmodifiableList(answers); } @Test public void shouldUpdateAnswerInQuestion() {
Answer class:
public class Answer { private long id; private String description; private Boolean correct; ... }
source share