정적 팩토리

박경희·2025년 4월 23일
0

공부를 해보자

목록 보기
36/40

네이밍 정리

용도 메서드명 예시
DTO → Entity toEntity()
Entity → DTO from(entity: Entity)
두 인자 이상 필요 of(request, team, createdBy) 도 자주 씀


1. toEntity() – DTO → Entity 변환

주로 CreateRequest / UpdateRequest 같은 요청 DTO에서
도메인 객체로 변환할 때 사용.

data class ContiCreateRequest(...) {
    companion object {
        fun toEntity(request: ContiCreateRequest, team: Team, createdBy: Long): Conti {
            return Conti(
                title = request.title,
                date = request.date,
                lyrics = request.lyrics,
                sheetMusicUrl = request.sheetMusicUrl ?: "",
                musicLink = request.musicLink ?: "",
                team = team,
                createdBy = createdBy
            )
        }
    }
}
  • 장점: 요청 처리 로직(Service)에서는 DTO에만 의존하고,
    Entity 생성은 전적으로 DTO 내부에서 처리하니 가독성과 유지보수성이 향상

2. from(entity) – Entity → Response DTO 변환

Entity → 응답 DTO로 변환할 때 주로 사용.
예: Conti → ContiResponse, ContiDetailResponse 등

data class ContiResponse(
    val id: Long,
    val title: String,
    val date: LocalDate
) {
    companion object {
        fun from(entity: Conti): ContiResponse {
            return ContiResponse(
                id = entity.id!!,
                title = entity.title,
                date = entity.date
            )
        }
    }
}
  • 장점: 응답 DTO가 “어떤 정보를 어떻게 노출할지”를 직접 정의할 수 있어서 보안 + 책임 분리가 잘 됨

3. of(...) – 복잡한 입력 값이 여럿일 때 (Entity, DTO, 외부 인자 등)

DTO + 연관 객체들 + 외부 파라미터가 함께 필요한 경우
즉, 생성자에 들어가는 인자가 많고, 단순 toEntity()보다 컨텍스트가 섞이는 경우에 좋음

data class ContiCreateRequest(...) {
    companion object {
        fun of(request: ContiCreateRequest, team: Team, userId: Long): Conti {
            return Conti(
                title = request.title,
                date = request.date,
                lyrics = request.lyrics,
                sheetMusicUrl = request.sheetMusicUrl ?: "",
                musicLink = request.musicLink ?: "",
                team = team,
                createdBy = userId
            )
        }
    }
}
  • toEntity()보다는 더 유연하고 상황지향적인 이름이라서 of()를 쓰는 경우도 많다.

메서드 변환 패턴 정리

메서드위치사용 시기설명
toEntity()Request DTO → Entity생성/수정 요청 처리 시가장 많이 쓰는 기본형
from()Entity → Response DTO응답 DTO 만들 때응답 포맷을 깔끔하게 분리
of()복합 상황 전용여러 인자 필요 시DTO + 연관 Entity + 외부 파라미터 등

효과 및 이유

효과이유
코드 간결함생성자 직접 호출보다 깔끔
책임 분리변환 책임은 DTO에서, 저장 책임은 Service에서
유지보수 용이Conti 생성 로직 수정 시 DTO 안에서만 변경 가능
테스트 분리 가능toEntity() 단독 테스트 가능

주요 패턴 예시

패턴역할예시 위치
toEntity()DTO → Entity 변환 (초기 생성)CreateRequest.toEntity(...)
from()Entity → DTO 변환 (조회 응답)Response.from(entity)
update()Entity 내부 상태 변경entity.update(...)

0개의 댓글