Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BE] refactor: question 타입과 답변 내용 일치 검증 및 매핑 로직 개선 #958

Merged
merged 13 commits into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ public record ReviewAnswerRequest(
@Nullable
String text
) {
public boolean hasTextAnswer() {
return text != null && !text.isEmpty();

public boolean hasNoText() {
return text == null || text.isBlank();
}

public boolean hasCheckboxAnswer() {
return selectedOptionIds != null && !selectedOptionIds.isEmpty();
public boolean hasNoSelectedOptions() {
return selectedOptionIds == null || selectedOptionIds.isEmpty();
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package reviewme.review.service.mapper;

import reviewme.template.domain.QuestionType;
import reviewme.review.domain.Answer;
import reviewme.review.service.dto.request.ReviewAnswerRequest;
import reviewme.template.domain.QuestionType;

public interface AnswerMapper {
public abstract class AnswerMapper {

boolean supports(QuestionType questionType);
public abstract boolean supports(QuestionType questionType);

Answer mapToAnswer(ReviewAnswerRequest answerRequest);
public abstract Answer mapToAnswer(ReviewAnswerRequest answerRequest);
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package reviewme.review.service.mapper;

import org.springframework.stereotype.Component;
import reviewme.template.domain.QuestionType;
import reviewme.review.domain.CheckboxAnswer;
import reviewme.review.service.dto.request.ReviewAnswerRequest;
import reviewme.review.service.exception.CheckBoxAnswerIncludedTextException;
import reviewme.template.domain.QuestionType;

@Component
public class CheckboxAnswerMapper implements AnswerMapper {
public class CheckboxAnswerMapper extends AnswerMapper {

@Override
public boolean supports(QuestionType questionType) {
Expand All @@ -16,8 +15,8 @@ public boolean supports(QuestionType questionType) {

@Override
public CheckboxAnswer mapToAnswer(ReviewAnswerRequest answerRequest) {
if (answerRequest.text() != null) {
throw new CheckBoxAnswerIncludedTextException(answerRequest.questionId());
if (answerRequest.hasNoSelectedOptions()) {
return null;
}
return new CheckboxAnswer(answerRequest.questionId(), answerRequest.selectedOptionIds());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,20 +62,10 @@ private List<Answer> getAnswersByQuestionType(ReviewRegisterRequest request) {

private Answer mapRequestToAnswer(Map<Long, Question> questions, ReviewAnswerRequest answerRequest) {
Question question = questions.get(answerRequest.questionId());

if (question == null) {
throw new SubmittedQuestionNotFoundException(answerRequest.questionId());
}

// TODO: 아래 코드를 삭제해야 한다
if (question.isSelectable() && answerRequest.selectedOptionIds() != null && answerRequest.selectedOptionIds().isEmpty()) {
return null;
}
if (!question.isSelectable() && answerRequest.text() != null && answerRequest.text().isEmpty()) {
return null;
}
// END

nayonsoso marked this conversation as resolved.
Show resolved Hide resolved
AnswerMapper answerMapper = answerMapperFactory.getAnswerMapper(question.getQuestionType());
return answerMapper.mapToAnswer(answerRequest);
donghoony marked this conversation as resolved.
Show resolved Hide resolved
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package reviewme.review.service.mapper;

import org.springframework.stereotype.Component;
import reviewme.template.domain.QuestionType;
import reviewme.review.domain.TextAnswer;
import reviewme.review.service.dto.request.ReviewAnswerRequest;
import reviewme.review.service.exception.TextAnswerIncludedOptionItemException;
import reviewme.template.domain.QuestionType;

@Component
public class TextAnswerMapper implements AnswerMapper {
public class TextAnswerMapper extends AnswerMapper {

@Override
public boolean supports(QuestionType questionType) {
Expand All @@ -16,12 +15,9 @@ public boolean supports(QuestionType questionType) {

@Override
public TextAnswer mapToAnswer(ReviewAnswerRequest answerRequest) {
if (!answerRequest.hasTextAnswer()) {
if (answerRequest.hasNoText()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이것만 검증하면 질문의 타입이 TEXT 이고, text와 selectedOptionIds 둘 다 있는 요청일때 TextAnswer 생성되지 않나요? (반대의 경우도 동일)

둘 다 들어온 경우에는 등록을 하면 안되지 않을까 합니다. (정상적이지 않은 요청)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#958 (comment)

이거 확인해주세용~!

Copy link
Contributor Author

@nayonsoso nayonsoso Nov 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

그리고 본문에서
이유1) 오버라이드를 할 이유가 없는 함수를 final 로 두려고
이유2) 외부에서 호출해서 사용할 필요가 없는 함수를 protected 로 두려고
이 내용은 어디에 해당된느건가요..?

처음에는 AnswerMapper에서 '질문의 타입에 해당하는 답변이 오지 않았을 때의 검증'을 잘 하기 위해서 템플릿 메서드 패턴을 사용했었습니다. 그리고 이때 final 함수가 필요했습니다. 그런데 리뷰를 반영하며 이 검증을 하지 않게 되면서 삭제했습니다😊
관련 커밋 : 4b2bbd1

그리고 protected 키워드도 리뷰를 반영하며, 사용하지 않는 쪽으로 바뀌었습니다!
관련 코멘트 : #958 (comment)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#958 (comment)
관련해서 의견 남겼어요~ 다음 의견에 대한 결론이 제 결론과 다르더라도 어프룹 할게요. 확인만 해주세요~

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

추가로 산초에게 질문을 하나만 더할게요, (단순 궁금)

"AnswerMapper 를 인터페이스에서 추상 클래스로 바꿨는데요, 적절하다고 생각하시나요?" 이 부분에서
이유 3은 저도 공감합니다.
그리고 이유 1이유 2는 사라진 상태인데요. 그럼 이유 3만으로 추상 클래스가 적절하다고 생각되어 바뀌는 부분인가요? 타입만 변경되고 다른건 변경되는 게 없어보여요.

Copy link
Contributor Author

@nayonsoso nayonsoso Nov 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사실 이 경우 인터페이스로 하던, 추상클래스로 하던 문제가 되진 않아요.
그런데 저는 의미상 추상클래스에 더 가깝다 생각했습니다.
인터페이스는 다중 구현이 가능하므로 '기능'이나 '명세'에 초점이 맞춰져있다면 (HAS-A)
추상클래스는 단일 상속만 가능하므로 '소속'을 의미한다고 생각합니다. (IS-A)

그런데 지금 다시 생각하니, AnswerMapper 가 중복 코드를 줄이는 구현을 제공하지 않는 이상
추상클래스로 할 이유도 없는 것 같긴 합니다😅
생각을 바꾼 계기는, 자바의 컬렉션을 생각해봤을 때 ArrayList 가
인터페이스 List 를 구현함으로써 기능에 대한 명세를 지키고,
추상 클래스 AbstractList 를 상속함으로써 중복되는 구체 메서드를 재사용했다는 것을 떠올렸어요.
그러므로 다시 인터페이스로 바꾸도록 하겠습니다😊

return null;
}
if (answerRequest.selectedOptionIds() != null) {
throw new TextAnswerIncludedOptionItemException(answerRequest.questionId());
}
return new TextAnswer(answerRequest.questionId(), answerRequest.text());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,23 @@
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import reviewme.template.domain.QuestionType;
import reviewme.review.domain.Answer;
import reviewme.review.service.dto.request.ReviewAnswerRequest;
import reviewme.template.domain.QuestionType;

@ExtendWith(OutputCaptureExtension.class)
class AnswerMapperFactoryTest {

private final AnswerMapper answerMapper = new AnswerMapper() {

@Override
public boolean supports(QuestionType questionType) {
return questionType == QuestionType.CHECKBOX;
public Answer mapToAnswer(ReviewAnswerRequest answerRequest) {
return null;
}

@Override
public Answer mapToAnswer(ReviewAnswerRequest answerRequest) {
return null;
public boolean supports(QuestionType questionType) {
return questionType == QuestionType.CHECKBOX;
}
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package reviewme.review.service.mapper;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import reviewme.review.domain.CheckboxAnswer;
import reviewme.review.domain.CheckboxAnswerSelectedOption;
import reviewme.review.service.dto.request.ReviewAnswerRequest;
import reviewme.review.service.exception.CheckBoxAnswerIncludedTextException;

class CheckboxAnswerMapperTest {

Expand All @@ -28,16 +28,17 @@ class CheckboxAnswerMapperTest {
.containsExactly(1L, 2L, 3L);
}

@Test
void 체크박스_답변_요청에_텍스트가_포함되어_있으면_예외를_발생시킨다() {
@ParameterizedTest
@NullAndEmptySource
void 체크박스_답변이_비어있는_경우_null로_매핑한다(List<Long> selectedOptionIds) {
// given
ReviewAnswerRequest request = new ReviewAnswerRequest(1L, List.of(1L, 2L, 3L), "text");
ReviewAnswerRequest request = new ReviewAnswerRequest(1L, selectedOptionIds, null);
CheckboxAnswerMapper mapper = new CheckboxAnswerMapper();

// when
CheckboxAnswerMapper mapper = new CheckboxAnswerMapper();
CheckboxAnswer actual = mapper.mapToAnswer(request);

// then
assertThatThrownBy(() -> mapper.mapToAnswer(request))
.isInstanceOf(CheckBoxAnswerIncludedTextException.class);
assertThat(actual).isNull();
nayonsoso marked this conversation as resolved.
Show resolved Hide resolved
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertAll;
import static reviewme.fixture.OptionGroupFixture.선택지_그룹;
import static reviewme.fixture.OptionItemFixture.선택지;
import static reviewme.fixture.QuestionFixture.서술형_옵션_질문;
Expand All @@ -16,12 +15,6 @@
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import reviewme.template.domain.OptionGroup;
import reviewme.template.domain.OptionItem;
import reviewme.template.domain.Question;
import reviewme.template.repository.OptionGroupRepository;
import reviewme.template.repository.OptionItemRepository;
import reviewme.template.repository.QuestionRepository;
import reviewme.review.domain.CheckboxAnswer;
import reviewme.review.domain.Review;
import reviewme.review.domain.TextAnswer;
Expand All @@ -31,7 +24,13 @@
import reviewme.reviewgroup.domain.ReviewGroup;
import reviewme.reviewgroup.repository.ReviewGroupRepository;
import reviewme.support.ServiceTest;
import reviewme.template.domain.OptionGroup;
import reviewme.template.domain.OptionItem;
import reviewme.template.domain.Question;
import reviewme.template.domain.Section;
import reviewme.template.repository.OptionGroupRepository;
import reviewme.template.repository.OptionItemRepository;
import reviewme.template.repository.QuestionRepository;
import reviewme.template.repository.SectionRepository;
import reviewme.template.repository.TemplateRepository;

Expand Down Expand Up @@ -60,7 +59,7 @@ class ReviewMapperTest {
private TemplateRepository templateRepository;

@Test
void 텍스트가_포함된_리뷰를_생성한다() {
void 서술형_답변을_매핑한다() {
// given
ReviewGroup reviewGroup = reviewGroupRepository.save(리뷰_그룹());

Expand All @@ -81,7 +80,7 @@ class ReviewMapperTest {
}

@Test
void 체크박스가_포함된_리뷰를_생성한다() {
void 선택형_답변을_매핑한다() {
// given
ReviewGroup reviewGroup = reviewGroupRepository.save(리뷰_그룹());

Expand All @@ -106,57 +105,47 @@ class ReviewMapperTest {
}

@Test
void 필수가_아닌_질문에_답변이_없을_경우_답변을_생성하지_않는다() {
void 필수가_아닌_서술형_질문에_답변이_없으면_매핑하지_않는다() {
// given
ReviewGroup reviewGroup = reviewGroupRepository.save(리뷰_그룹());
Question question = questionRepository.save(서술형_옵션_질문());
Section section = sectionRepository.save(항상_보이는_섹션(List.of(question.getId())));
templateRepository.save(템플릿(List.of(section.getId())));

Question requiredTextQuestion = questionRepository.save(서술형_필수_질문());
Question optionalTextQuestion = questionRepository.save(서술형_옵션_질문());
ReviewAnswerRequest answerRequest = new ReviewAnswerRequest(question.getId(), null, "");
ReviewRegisterRequest reviewRegisterRequest = new ReviewRegisterRequest(
reviewGroup.getReviewRequestCode(), List.of(answerRequest));

Question requeiredCheckBoxQuestion = questionRepository.save(선택형_필수_질문());
OptionGroup optionGroup1 = optionGroupRepository.save(선택지_그룹(requeiredCheckBoxQuestion.getId()));
OptionItem optionItem1 = optionItemRepository.save(선택지(optionGroup1.getId()));
OptionItem optionItem2 = optionItemRepository.save(선택지(optionGroup1.getId()));
// when
Review review = reviewMapper.mapToReview(reviewRegisterRequest);

Question optionalCheckBoxQuestion = questionRepository.save(선택형_옵션_질문());
OptionGroup optionGroup2 = optionGroupRepository.save(선택지_그룹(optionalCheckBoxQuestion.getId()));
OptionItem optionItem3 = optionItemRepository.save(선택지(optionGroup2.getId()));
OptionItem optionItem4 = optionItemRepository.save(선택지(optionGroup2.getId()));
// then
assertThat(review.getAnswersByType(TextAnswer.class))
.extracting(TextAnswer::getQuestionId)
.isEmpty();
}

Section section = sectionRepository.save(항상_보이는_섹션(
List.of(requiredTextQuestion.getId(), optionalTextQuestion.getId(),
requeiredCheckBoxQuestion.getId(), optionalCheckBoxQuestion.getId())));
@Test
void 필수가_아닌_선택형_질문에_답변이_없으면_매핑하지_않는다() {
// given
ReviewGroup reviewGroup = reviewGroupRepository.save(리뷰_그룹());
Question question = questionRepository.save(선택형_옵션_질문());
OptionGroup optionGroup = optionGroupRepository.save(선택지_그룹(question.getId()));

Section section = sectionRepository.save(항상_보이는_섹션(List.of(question.getId())));
templateRepository.save(템플릿(List.of(section.getId())));

String textAnswer = "답".repeat(20);
ReviewAnswerRequest requiredTextAnswerRequest = new ReviewAnswerRequest(
requiredTextQuestion.getId(), null, textAnswer
);
ReviewAnswerRequest optionalTextAnswerRequest = new ReviewAnswerRequest(
optionalTextQuestion.getId(), null, ""
);
ReviewAnswerRequest requiredCheckBoxAnswerRequest = new ReviewAnswerRequest(
requeiredCheckBoxQuestion.getId(), List.of(optionItem1.getId()), null
);
ReviewAnswerRequest optionalCheckBoxAnswerRequest = new ReviewAnswerRequest(
optionalCheckBoxQuestion.getId(), List.of(), null
);
ReviewRegisterRequest reviewRegisterRequest = new ReviewRegisterRequest(reviewGroup.getReviewRequestCode(),
List.of(requiredTextAnswerRequest, optionalTextAnswerRequest,
requiredCheckBoxAnswerRequest, optionalCheckBoxAnswerRequest));
ReviewAnswerRequest answerRequest = new ReviewAnswerRequest(question.getId(), List.of(), null);
ReviewRegisterRequest reviewRegisterRequest = new ReviewRegisterRequest(
reviewGroup.getReviewRequestCode(), List.of(answerRequest));

// when
Review review = reviewMapper.mapToReview(reviewRegisterRequest);

// then
assertAll(
() -> assertThat(review.getAnswersByType(TextAnswer.class))
.extracting(TextAnswer::getQuestionId)
.containsExactly(requiredTextQuestion.getId()),
() -> assertThat(review.getAnswersByType(CheckboxAnswer.class))
.extracting(CheckboxAnswer::getQuestionId)
.containsExactly(requeiredCheckBoxQuestion.getId())
);
assertThat(review.getAnswersByType(CheckboxAnswer.class))
.extracting(CheckboxAnswer::getQuestionId)
.isEmpty();
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,16 @@
package reviewme.review.service.mapper;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import reviewme.review.domain.TextAnswer;
import reviewme.review.service.dto.request.ReviewAnswerRequest;
import reviewme.review.service.exception.TextAnswerIncludedOptionItemException;

class TextAnswerMapperTest {

/*
TODO: Request를 추상화해야 할까요?
떠오르는 방법은 아래와 같습니다.
1: static factory method를 사용 -> 걷잡을 수 없어지지 않을까요?
2: 다른 방식으로 추상화 ?
*/

@Test
void 텍스트_답변을_요청으로부터_매핑한다() {
// given
Expand All @@ -31,16 +24,18 @@ class TextAnswerMapperTest {
assertThat(actual.getContent()).isEqualTo("text");
}

@Test
void 텍스트_답변_요청에_옵션이_포함되어_있으면_예외를_발생시킨다() {
@ParameterizedTest
@NullSource
@ValueSource(strings = {"", " "})
void 텍스트_답변이_비어있는_경우_null로_매핑한다(String text) {
// given
ReviewAnswerRequest request = new ReviewAnswerRequest(1L, List.of(1L), "text");
ReviewAnswerRequest request = new ReviewAnswerRequest(1L, null, text);

// when
TextAnswerMapper mapper = new TextAnswerMapper();
TextAnswer actual = mapper.mapToAnswer(request);

// then
assertThatThrownBy(() -> mapper.mapToAnswer(request))
.isInstanceOf(TextAnswerIncludedOptionItemException.class);
assertThat(actual).isNull();
}
}