리팩터링 Key (제네릭, 생성자 편)

최지혜·2022년 11월 23일
0

java

목록 보기
25/33

제네릭을 사용하여 테스트 중복 제거

대표적으로 중복이 발생하는 부분은 도메인별 CRUD(Create, Read, Update, Delete)메소드

Post에 대한 코드뿐 아니라 모든 도메인의 Get, Put, Patch, Delete 요청에 대한 부분이 중복

 protected <T> ResultActions doPost(String path, T request) throws Exception {
        return mockMvc.perform(post(**path**)
            .header(HttpHeaders.AUTHORIZATION, LoginFixture.getUserTokenHeader())
            .contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsBytes(request))
        )
            .andExpect(status().isCreated())
            .andExpect(header().string(HttpHeaders.LOCATION, path + "/1"));
}

protected <T> ResultActions doPut(**String path, T request**) throws Exception {
        return mockMvc.perform(put(**path**)
            .header(HttpHeaders.AUTHORIZATION, LoginFixture.getUserTokenHeader())
            .contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsBytes(**request**))
        )
            .andExpect(status().isNoContent());
}

주생성자와 부생성자

1. 부생성자

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student(Person person) {
        this(person.getName(), person.getAge());
    }
}

위와 같이 구현하게 되면 Person 객체를 다음과 같이 간단하게 생성

Person nick = new Person("nick", 8);
Student personToStudent = new Student(nick);

2. score 추가

student - score가 불필요한 경우가 있을 때

public class Student {
    private String name;
    private int age;
    private int score;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student(String name, int age, int score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public Student(StudentRequest studentRequest) {
        this(studentRequest.getName(), studentRequest.getAge());
    }
    
    public void addAge(int adder) {
        this.age += adder;
    }
}

아래와 같이 주생성자와 부생성자를 활용하는 this를 이용해 코드의 중복을 피할 수도 있습니다.

    public Student(String name, int age, int score) {
        this(name, age);
        this.score = score;
    }

생성자의 추가를 두려워하지 않으면 객체를 사용함에 있어 유연성과 확장성이 커진다!!!

3. 정적 팩토리 메서드

(score 사용 시에 null이 들어가있어 객체를 사용할 때 자칫하면 NullPointerException이 발생할 수도 있기 때문)

  • 객체의 생성자를 숨기면서, 객체를 만들어낼 수 있는 메서드
  • 이름을 가짐으로써 객체 생성의 의도를 드러냄.
  • 여러 생성자가 생겼을 때 명확한 의도를 가진 이름으로 구분
public class Student {
    private String name;
    private int age;
    private int score;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    private Student(String name, int age, int score) {
        this(name, age);
        this.score = score;
    }

    public **static** Student withScore(String name, int age, int score) {
        return new Student(name, age, score);
    }
}

출처: 테코빌 기술블로그 참고

profile
매일 성장하는 개발자

0개의 댓글