개요
이번 포스팅에서는 API 응답 DTO에 Generic을 이용해 개선해보는 시간을 가져보겠습니다.
기존 API 응답 DTO
@Data
public class ApiResponse implements Serializable {
@Schema(description = "서버 정의 상태코드" , example = "1")
private String statusCode;
@Schema(description = "서버 정의 메세지" , example = "1")
private String message;
@Schema(description = "데이터")
private Object data;
@Builder
public ApiResponse(String statusCode, String message, Object data) {
this.statusCode = statusCode;
this.message = message;
this.data = data;
}
}
기존에는 ApiResonse의 Data가 Object Class를 사용하는 구조였습니다.
Object Class를 사용하면서 불편한 점이 있었습니다.
- Object Class 사용시 명시적 형변환을 해줘야한다.
- 컴파일 타임에서 에러를 잡을 수 없다. => 런타임에 치명적인 에러를 만날 수도 있다.
예시를 보겠습니다.
ApiResponse response = branchService.getRestrictionsByCountry(request);
List<CountryRestrictions> data = (List<CountryRestrictions>) response.getData();
response.getData()가 반환하는 타입이 Object이기 때문에 (List<CountryRestrictions>) 캐스팅은 런타임에만 체크됩니다. 즉 getData()가 List<CountryRestrictions>가 아니면 ClassCastException이 발생할 수 있습니다. 또 개발자가 명시적으로 형변환을 해줘야하는 상황이 발생합니다.
위와 같은 이유들로 ApiResonse를 Generic을 사용해 개선해보겠습니다.
@Data
public class ApiResponse<T> implements Serializable {
@Schema(description = "서버 정의 상태코드" , example = "1")
private String statusCode;
@Schema(description = "서버 정의 메세지" , example = "1")
private String message;
@Schema(description = "데이터")
private T data;
@Builder
public ApiResponse(String statusCode, String message, T data) {
this.statusCode = statusCode;
this.message = message;
this.data = data;
}
}
Generic을 적용함에 따라 기존 Builder 패턴에도 타입을 명시해줘야 합니다.
return ApiResponse.<IpGeolocationApiResponse>builder()
.statusCode(StatusCode.SUCCESS.getStatusCode())
.message(StatusCode.SUCCESS.getMessage())
.data(ipGeolocationApiResponse)
.build();
ApiResponse<List<CountryRestrictions>> response = branchService.getRestrictionsByCountry(request);
List<CountryRestrictions> data = response.getData();
이제 위와 같이 명시적 형변환이 필요 없어지고, 런타임에 에러가 발생할 수 있는 상황을 방지할 수 있습니다.
레포지토리 주소
'Project > Gameple' 카테고리의 다른 글
| [Project - Gameple] Project Gameple(8) - 프로모션 API - 사전예약 API (0) | 2023.09.17 |
|---|---|
| [Project - Gameple] Project Gameple(7) - 브랜치 API - IP 기반 국가 코드 조회 API (0) | 2023.09.13 |
| [Project - Gameple] Project Gameple(6) - Game Entity 설계 (0) | 2023.07.16 |
| [Project - Gameple] Project Gameple(5) - Spring Security 적용하기 (0) | 2023.07.07 |
| [Project - Gameple] Project Gameple(4) - Swagger 적용하기 (0) | 2023.06.29 |