이펙티브자바의 목차
생성자 대신 팩토리 메서드를 고려해라
Item: Consider static factory methods instead of constructors
장점 1. 이름을 가질 수 있다.
package com.everyparking.api.dto;
import lombok.Builder;
import lombok.Data;
import org.springframework.http.HttpStatus;
@Data
@Builder
public class DefaultResponseDtoEntity {
private String message;
private Object data;
private HttpStatus httpStatus;
private DefaultResponseDtoEntity() {}
public static DefaultResponseDtoEntity of(HttpStatus httpStatus, String message) {
return DefaultResponseDtoEntity
.builder()
.httpStatus(httpStatus)
.message(message)
.build();
}
public static DefaultResponseDtoEntity of(HttpStatus httpStatus, String message, Object data) {
return DefaultResponseDtoEntity
.builder()
.httpStatus(httpStatus)
.message(message)
.data(data)
.build();
}
public static DefaultResponseDtoEntity ok(String message) {
return DefaultResponseDtoEntity
.builder()
.httpStatus(HttpStatus.OK)
.message(message)
.build();
}
public static DefaultResponseDtoEntity ok(String message, Object data) {
return DefaultResponseDtoEntity
.builder()
.httpStatus(HttpStatus.OK)
.message(message)
.data(data)
.build();
}
}
장점 2. 생성할 때마다 인스턴스를 만들지 않아도된다.
package com.everyparking.data.place.service;
import com.everyparking.api.dto.DefaultResponseDtoEntity;
import com.everyparking.api.dto.PlaceRequestDto;
import com.everyparking.data.place.domain.Place;
import com.everyparking.data.place.repository.PlaceRepository;
import com.everyparking.data.user.service.valid.JwtTokenUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
@Transactional
public class PlaceService {
private final PlaceRepository placeRepository;
private final JwtTokenUtils jwtTokenUtils;
public DefaultResponseDtoEntity addPlace(String token, PlaceRequestDto dto) {
var user = jwtTokenUtils.getUserByToken(token);
var data = placeRepository
.save(Place.dtoToEntity(user,
dto.getPlaceName(),
dto.getMapAddr(),
dto.getMessage(),
dto.getMapX(),
dto.getMapY(),
dto.getImgUrl()));
return DefaultResponseDtoEntity
.of(HttpStatus.CREATED, "주차공간 등록 성공", data);
}
public DefaultResponseDtoEntity getAllPlace() {
return DefaultResponseDtoEntity
.ok("성공", placeRepository.findAll());
}
}
'Spring > Spring Boot' 카테고리의 다른 글
[Spring Boot] 요청, 응답 시 Json에 루트 추가하기 (0) | 2022.09.24 |
---|---|
객체지향의 사실과 오해를 읽으며 코드 리팩토링 (0) | 2022.09.19 |
[학교 관리 프로젝트] 도메인 단위 테스트와 테스트 코드를 가독성있고 빠르게 작성하는 방법 (0) | 2022.08.31 |
[게시판 RESTful API] - RestController와 Service를 구현해보자 (3) (0) | 2022.08.20 |
[게시판 RESTful API] - domain을 만들며 Entity를 알아보자. (2) (0) | 2022.08.20 |