개발자가 말대꾸?
봄 백엔드 개발일기
개발자가 말대꾸?
전체 방문자
오늘
어제
  • 분류 전체보기 (42)
    • 알고리즘 공부 (13)
    • 디자인 패턴 공부 (1)
    • Spring (15)
      • Spring Boot (12)
      • Spring Data (1)
      • Spring Security (1)
    • Java (2)
    • MySQL (5)
    • EDITOR (3)
      • Intellij (3)
      • vscode (0)
    • 기타 (3)
      • 에러 (3)
      • 감상문 (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • JPA 여러 컬럼 Unique
  • 라이브 템플릿
  • BasicAuthorization
  • SpringBoot
  • Java
  • JPA 여러 컬럼 유니크
  • 권한 프로그래밍
  • intellij live templates
  • GrantedAuthority
  • 프로그래머스
  • mysql
  • BasicAuthenticationFilter
  • 인텔리제이 사용법
  • IntelliJ
  • Jpa 다중 제약조건 설정
  • intelliJ 단축키
  • UserDetails 도메인
  • jsp
  • 프로그래머스 2단계
  • RabbitMQ Kafka 차이
  • MSA 아키텍처에서 Config Server의 변경 사항을 MSA에게 전달하는 방법
  • spring
  • rest-api
  • SpringSecurity 프로젝트
  • Python
  • 인텔리제이 좋은점
  • JPA
  • spring boot
  • 코드 템플릿
  • JPA Unique 제약조건

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
개발자가 말대꾸?

봄 백엔드 개발일기

Spring/Spring Boot

Effective Java를 읽으며 코드 리펙토링

2022. 10. 8. 22:39

이펙티브자바의 목차

 

영어공부한다고 원서랑 번역본을 같이 보는중..

 

 

 

생성자 대신 팩토리 메서드를 고려해라

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
    'Spring/Spring Boot' 카테고리의 다른 글
    • [Spring Boot] 요청, 응답 시 Json에 루트 추가하기
    • 객체지향의 사실과 오해를 읽으며 코드 리팩토링
    • [학교 관리 프로젝트] 도메인 단위 테스트와 테스트 코드를 가독성있고 빠르게 작성하는 방법
    • [게시판 RESTful API] - RestController와 Service를 구현해보자 (3)
    개발자가 말대꾸?
    개발자가 말대꾸?
    - ing9990.com - 열정적인 ENTP - 주말 코딩, 퇴근 코딩 ing9990

    티스토리툴바