대표적으로 중복이 발생하는 부분은 도메인별 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());
}
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);
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;
}
생성자의 추가를 두려워하지 않으면 객체를 사용함에 있어 유연성과 확장성이 커진다!!!
(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);
}
}
출처: 테코빌 기술블로그 참고