메서드 체이닝

메서드 체이닝

메서드에 메서드에 메서드에...

·

2 min read

여러 메서드 호출을 연결해 하나의 실행문으로 표현하는 문법 형태

디자인 패턴 중 빌더(Builder) 패턴에서 볼 수 있다.

장점

코드가 간결해져 하나의 문장처럼 읽히게 할 수 있어, 장기적으로 유지보수에 도움이 됨

매개 변수 개수, 입력 순서 제약없이 저장됨

단점

하나의 라인에 너무 많은 일이 일어날 수 있어 디버깅을 하기가 어려움

하나의 객체 반환이 목적 아닌 타 객체 메서드 접근을 시도하면 기차 충돌(디미터 법칙 위배)

예제

public class OrderTest {
    public static void main(String[] args) {
        long no = 202011020003L;
        int phone = 01023450001;
        String address = "서울시 강남구 역삼동 111-333";
        int date = 20201102;
        int time = 130258;
        int price = 35000;
        int num = 0003;

        Order order = new Order.Builder()
                .phone(phone).no(no).address(address)
                .date(date).time(time).price(price)
                .num(num).build();

        System.out.print(order);
    }
}
public class Order {
    private long no;
    private int phone;
    private String address;
    private int date;
    private int time;
    private int price;
    private int num;

    public Order(Builder builder) {
        this.no = builder.no;
        this.phone = builder.phone;
        this.address = builder.address;
        this.date = builder.date;
        this.time = builder.time;
        this.price = builder.price;
        this.num = builder.num;
    }

    @Override
    public String toString() {
        return "주문 접수 번호 : " + no + '\n' +
                "주문 핸드폰 번호 : " + phone + '\n' +
                "주문 집 주소 : " + address + '\n' +
                "주문 날짜 : " + date + '\n' +
                "주문 시간 : " + time + '\n' +
                "주문 가격 : " + price + '\n' +
                "메뉴 번호 : " + num;
    }

    static class Builder {

        private long no;
        private int phone;
        private String address;
        private int date;
        private int time;
        private int price;
        private int num;

        public Builder no(long no) {
            this.no = no;
            return this;
        }

        public Builder phone(int phone) {
            this.phone = phone;
            return this;
        }

        public Builder address(String address) {
            this.address = address;
            return this;
        }

        public Builder date(int date) {
            this.date = date;
            return this;
        }

        public Builder time(int time) {
            this.time = time;
            return this;
        }

        public Builder price(int price) {
            this.price = price;
            return this;
        }

        public Builder num(int num) {
            this.num = num;
            return this;
        }

        public Order build() {
            return new Order(this);
        }
    }
}
주문 접수 번호:202011020003
주문 핸드폰 번호:139350017
주문 집 주소:서울시 강남구 역삼동 111-333
주문 날짜:20201102
주문 시간:130258
주문 가격:35000
메뉴 번호:3