우린 Controller, Service, Repository 구조로 코드를 나눴다.

혹시 지금까지 정말 문제없이 잘 구현해왔을까?

1

내가 찾아보고 결정했던 유효성 검사의 위치는 아래와 같다.

Service에서는 DTO를 Entity로 전환하는 단순 로직만 갖고 있고, 그 외의 가공은 DTO에서 Mapper를 통해 분리하는 것이 좋겠다고 생각했습다.

Mapper는 오히려 보기 어려워진다고 생각해 DTO 내부에 Mapper 역할을 하는 정적 팩토리 메소드를 선언해야겠다고 생각.

public record PostListResponse(
        List<PostSummary> posts
) {
    public record PostSummary(
            String postTitle,
            String userName
    ) {
    }
}

// PostService
    public PostListResponse getAllPost(Long userId) {
        validateUserIdExist(userId);
        List<Post> postList = postRepository.findAll();
        List<PostListResponse.PostSummary> postSummaries = postList.stream()
                .map(post -> new PostListResponse.PostSummary(
                        post.getTitle(),
                        post.getUser().getName()
                ))
                .toList();
        return new PostListResponse(postSummaries);
    }

이랬던 코드를 다음과 같이 수정했다.

public record PostListResponse(
        List<PostSummary> posts
) {
    public record PostSummary(
            String postTitle,
            String userName
    ) {
    }

    public static PostListResponse from(List<Post> postList) {
        List<PostSummary> summaries = postList.stream()
                .map(post -> new PostSummary(
                        post.getTitle(),
                        post.getUser().getName()
                ))
                .toList();

        return new PostListResponse(summaries);
    }
}