본래 커맨드 패턴이란 어떤 객체가 다른 객체에게 어떠한 작업을 수행하도록 지시할 때, 이것을 기억해 뒀다가 재사용할 수 있도록 객체화하는 것을 말함

다만 여기서는 그 의미를 축소시켜 스프링 애플리케이션에서 Controller → Service 간 정보 전달 시에 사용하는 DTO 객체를 다루기로 함

public record CommentRequestDto(
        long postId,
        @Length(min = 1, max = 500, message = "댓글은 1~500자 사이로 입력해야 합니다.")
        String comment
) implements Dto {
}

이 정보는 컨트롤러에서 받아 서비스에 그 dto를 그대로 넘기거나, 혹은 필요한 정보를 분해해서 하나씩 전달하는 것이 가능함

@PostMapping("/{postId}/comments")
    public ResponseEntity<?> handleAddCommentRequest(@PathVariable long postId,
                                                     @RequestBody @Valid CommentRequestDto dto,
                                                     Authentication authentication){
        long memberId = authService.getMemberIdFromAuthentication(authentication);

				// 서비스에 필요한 정보 전달
        postService.createComment(postId, memberId, comment);
        
      // 나머지 로직 구현...

그러나 컨트롤러 → 서비스 간 정보 전달에도 DTO가 많이 사용된다고 함

이때 네이밍은 Command로 하는 것이 관례

public record CreateCommentCommand(
        long postId,
        long memberId,
        String content
) {
}

이렇게 하면 컨트롤러는 정보들을 객체화 하여 서비스에 전달하게 됨

사용할 때의 이점

DTO를 그대로 넘기는 방법과 비교: