예제 - 매칭 상태 변경(To 모집 완료, 모집 중) 메서드
IF 구문이 4가지가 된다. 🫠
MATCH_CANNOT_UPDATE_END
: 이 메서드는 경기 종료(END)로 변경 불가능
MATCH_ACCESS_DENIED
: 작성자 본인이 아니면 변경 불가능
MATCH_ALREADY_CHANGED_STATUS
: 같은 상태로 변경 불가능(모집 완료 → 모집 완료)
MATCH_ENDED
: 경기 종료 상태인 경우 변경 불가능
많은 걸 떠나서 Objects.equals 도 추가 되니 가독성이 너무 떨어짐.
@Transactional public void updateStatusExceptEnd(Long id, Long userId, MatchStatus status) { if (Objects.equals(status, MatchStatus.END)) { throw new BusinessException(ErrorCode.MATCH_CANNOT_UPDATE_END, MessageFormat.format("matchId = {0}, userId = {1}, status = {2}", id, userId, status)); } Match match = matchRepository.findById(id) .orElseThrow(() -> new EntityNotFoundException(ErrorCode.MATCH_NOT_FOUND, MessageFormat.format("matchId = {0}", id))); if (!Objects.equals(match.getUser().getId(), userId)) { throw new BusinessException(ErrorCode.MATCH_ACCESS_DENIED, MessageFormat.format("matchId = {0} , userId = {1}", id, userId)); } if (Objects.equals(match.getStatus(), status)) { throw new BusinessException(ErrorCode.MATCH_ALREADY_CHANGED_STATUS, MessageFormat.format("matchId = {0} , status = {1}", id, status)); } if (Objects.equals(match.getStatus(), MatchStatus.END)) { throw new BusinessException(ErrorCode.MATCH_ENDED, MessageFormat.format("matchId = {0} , status = {1}", id, status)); } match.updateStatus(status); }
방법 1. Entity 의 비지니스 로직 안에서 체크 및 예외 발생
match.updateStatus(status);
- 모든 상황 다 넣지 않더라도
MATCH_ACCESS_DENIED
,MATCH_ALREADY_CHANGED_STATUS
인 경우.. Entity로 빼둘 만한듯…? 🤔
방법 2. 체크 로직을 private 메서드로 분리
- 체크 로직 중복 되는 경우 제거 가능
- 명확한 네이밍으로 가독성 향상
if (!Objects.equals(match.getUser().getId(), userId)) { throw new BusinessException(ErrorCode.MATCH_ACCESS_DENIED, MessageFormat.format("matchId = {0} , userId = {1}", id, userId)); }
To.
checkIsAuthorOfMatch(match, userId); public void checkIsAuthorOfMatch(Match match, Long userId) { if (!Objects.equals(match.getUser().getId(), userId)) { throw new BusinessException(ErrorCode.MATCH_ACCESS_DENIED, MessageFormat.format("matchId = {0} , userId = {1}", id, userId)); } }
예시 네이밍이 좀 그래서 그렇지.. 잘 지으면 좋을지도?