메서드 체이닝이란 ?
.setxxx().setxxx() 같은 코드 패턴은 개발을 하면서 많이 보았지만 정확한 이 개념에 대해서 자세히 알지 못해서 정리하게 되었다.
메서드 체이닝(Method Chaining)이란 객체지향프로그램(OOP) 에서 메서드 호출을 연속적으로 이어서 호출하는 패턴을 말한다.
일반적으로 **Setter 메서드나 빌더 패턴(Builder Pattern)**에서 많이 사용된다.
1. 일반 방식 vs. 메서드 체이닝 방식 코드 차이
1) 일반적인 방식 ( 메서드 체이닝을 사용X)
class Person {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) { //void 로 반환하면 메서드 체이닝 불가능
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("Alice");
person.setAge(25);
}
}
2) 메서드 체이닝 적용 방식
class Person {
private String name;
private int age;
public Person setName(String name) {
this.name = name;
return this; // 현재 객체를 반환
}
public Person setAge(int age) {
this.age = age;
return this; // 메서드 체이닝을 사용하려면 this를 반환해야함.
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person()
.setName("Alice")
.setAge(25);
}
}
일반적인 방식은 직관적이고 디버깅이 쉬운 장점이 있지만, 코드가 길어질 수 있다.
메서드 체이닝 방식은 코드가 간결하지만, 중간 디버깅이 어려울 수 있다.
2. 메서드 체이닝을 어디에서 사용되는가 ?
1) 많이 사용되는 곳 builder Paterrn
class Person {
private String name;
private int age;
// 정적 내부 클래스 (Builder)
public static class Builder {
private String name;
private int age;
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setAge(int age) {
this.age = age;
return this;
}
public Person build() {
return new Person(this);
}
}
private Person(Builder builder) {
this.name = builder.name;
this.age = builder.age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person.Builder()
.setName("Alice") //메서드 체이닝
.setAge(25)
.build();
System.out.println(person);
}
}
🔹 빌더 패턴이 유용한 이유:
- 객체의 불변성(Immutable) 유지: setXXX() 없이 한 번에 설정 가능
- 유연한 객체 생성: 필요한 필드만 설정 가능
2) StringBuilder
String result = new StringBuilder()
.append("Hello, ")
.append("World!")
.toString();
System.out.println(result); // Hello, World!
3) Java Stream api
List<String> names = List.of("Alice", "Bob", "Charlie");
List<String> filteredNames = names.stream() .filter(name -> name.startsWith("A")) .map(String::toUpperCase) .collect(Collectors.toList());
System.out.println(filteredNames); // [ALICE]
4) spring boot responseEntity
return ResponseEntity.status(HttpStatus.OK) .header("Custom-Header", "value") .body("Success");
3. 주의 사항
기본 @Setter 사용시 메서드 체이닝 사용불가
(++ setter 어노테이션 붙여놓고 메서드 체이닝 하려고 하니까 안되어서 본 패턴을 찾아보게 되었다.)
1) 메서드 체이닝이 가능한 Lombok 설정 방법
@Accessors(chain = true) // ✅ 체이닝 활성화
ex) setName(“Alice”).setAge(25)
@Accessors(fluent = true, chain = true) // ✅ 메서드 체이닝 + 필드명 그대로 사용
ex) name(“Alice”).age(25)
'백엔드 back-end' 카테고리의 다른 글
[JAVA] Logger 선언: 정적(static) vs 인스턴스(instance) 방식의 차이, 권장방법? (1) | 2024.10.25 |
---|---|
[Spring] DTO & Entity 차이, 분리이유 ? (0) | 2024.09.25 |
[리팩토링] if-statemets 를 효율적이고 가독성있게 사용하는 방법 3가지 (1) | 2024.08.20 |
[Spring] @Value 어노테이션 값에 빨간줄 뜨는 이유? / 인식오류/ 해결방법 (0) | 2024.08.13 |
[JPA] 엔티티 클래스 테이터 타입 int, Integer 차이점/ null 값 오류 해결방법 (0) | 2024.08.05 |