Service 클래스에서 무언가의 정보를 반환할 때 ResponseDto를 사용하게되는데, 이 때 만약 필요한 필드가 복잡하지 않다면 우리에게 친숙한 Getter를 사용하여 코드가 덜 복잡하고 속도가 빨라질 수 있다.
return new ResponseDto(
product.getId(),
product.getProductName(),
);
하지만 만약 필드가 복잡하고 다중 스레드 환경에서 문제가 발생할 위험이 있을 경우에는 getter를 사용하는 것 보다 builder패턴을 사용하는 것이 권장되는데, 이는 builder패턴을 사용하면 불변 객체를 생성하기 때문에 불변성을 지킬 수 있기 때문이다.
return new ResponseDto.builder()
.productId(product.getProductId())
.productName(product.getProductName())
.price(product.getprice())
.quantity(product.getQuantity())
.description(product.getDescription())
.builder();
지금까지 무의식적으로 getter만을 사용하여 값을 반환했었지만 팀프로젝트를 진행하며 여러 사람들의 코드를 공유하다보니 새로운 사용법을 알게되고 추가적으로 사용이유와 활용범위도 알아보며 공부가 되었다.
추가적으로 RequestDto에서 필드 값을 받아올 때 Dto에 builder패턴으로 값을 가져와서 Controller에서 Service로 하나의 객체를 넘겨주어 책임을 분리하는 방법도 있다는 것을 알게되었다.
// Dto
public Product toEntity() {
return Product.builder()
.productId(productId)
.productName(productName)
.price(price)
.quantity(quantity)
.description(description)
.builder();
}
// Controller
public void createProduct(@RequestBody ProductCreateRequestDto rquestDto) {
Product product = requestDto.toEntity();
productService.createProduct(product);
}